355 views
3 3 votes

You are given an $n \times n$ matrix where each row and each column is sorted in ascending order. You need to search for a target element "x" in the matrix.

What is the best possible asymptotic bound in the worst case to solve this problem?

  1. $\Theta(\log n)$
     
  2. $\Theta(n)$
     
  3. $\Theta\left(n^2\right)$
     
  4. $\Theta(1)$

3 Answers

3 3 votes

This task can be done in $\theta(n)$ time using the following approach:
We have an $n \times n$ matrix:

  • Each row is sorted in ascending order (left $\rightarrow$ right).
     
  • Each column is sorted in ascending order (top $\rightarrow$ bottom).
     
  • Start from the top-right corner (row = 0, col = n-1).
     
  • Compare with target x. .

Rules:

1. If $\operatorname{arr}[\mathrm{row}][\mathrm{col}]==x \rightarrow$ Found.

2. If $\operatorname{arr}[\mathrm{row}][\mathrm{col}]>x \rightarrow$ Move left (col--).

3. If arr[row][col] $<x \rightarrow$ Move down (row++).

In the worst case:

  • We move $n-1$ steps down and $n-1$ steps left.
     
  • Total $=2(n-1)$ steps $=\Theta(n)$.
• reshown by
0 0 votes
N*N Matrix are Sorted in Both Direction

Then Use  Bineary Serch for First Col. and Then Row

For Row Log(n)+ For Coloum  Log(n)

O(Log n)

A is correct Answer
0 0 votes
answer is B  for sigle n array it take log n then for n2 it will take n  because in worst case scenario we have to traverse through n columns or rows
Answer:
Position:
Show:

Related questions

2 2 votes
1 1 answer
254
254 views
GO Classes asked Aug 28, 2025
254 views
A monkey is given $n$ piles of bananas, where the 'ith' pile has nums[i] bananas (nums is an array of size n ). An integer h represents the total time in hours to eat all...
1 1 vote
3 3 answers
285
285 views
GO Classes asked Aug 28, 2025
285 views
Alice has two sorted arrays $\mathrm{A}[1, \ldots, \mathrm{n}], \mathrm{B}[1, \ldots, \mathrm{n}+1]$. She knows that A is composed of distinct positive numbers, and B is ...
1 1 vote
3 3 answers
394
394 views
GO Classes asked Aug 28, 2025
394 views
A machine needs a maximum of $200$ seconds to sort $1000$ elements by Quick sort. The maximum time needed (in seconds) to sort $200$ elements will be approximately ______...
2 2 votes
2 2 answers
279
279 views
GO Classes asked Aug 28, 2025
279 views
Which of the following statements is/are not correct?(Here $o, \omega$ represents small-oh and small-omega, respectively.)The average-case time complexity of quicksort $=...