166 views
0 0 votes

You are given a sorted array of $n$ elements that has been rotated an unknown number of times $($e.g., $\verb|[4,5,6,7,0,1,2]|)$. You need to find a target element in this array. What is the most efficient worst-case time complexity to achieve this?

  1. $O(1)$
     
  2. $O(\log n)$
     
  3. $O(\sqrt{n})$
     
  4. $O(n)$

1 Answer

0 0 votes

Modified Binary Search: Even though the array is rotated, it still consists of two sorted subarrays.

Logic: In each step of the binary search, at least one half $($either $\verb|left|$ to $\verb|mid|$ or $\verb|mid|$ to $\verb|right|)$ must be sorted.

Execution: By checking which half is sorted and whether the target lies within that sorted range, we can discard half of the search space in each iteration.

Complexity: Since we reduce the search space by half each time, the complexity remains $O(\log n)$, identical to standard Binary Search.

Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
193
193 views
GO Classes asked Jan 20
193 views
In a Strictly Binary Tree $($also known as a Full Binary Tree$)$ where every node has either $0$ or $2$ children, if there are $L$ leaf nodes, what is the total number of...
0 0 votes
1 1 answer
214
214 views
GO Classes asked Jan 20
214 views
Consider an undirected graph $G$ with $V$ vertices and $E$ edges. If we perform a Breadth-First Search (BFS) starting from a source vertex $s$, which of the following sta...
2 2 votes
1 1 answer
177
177 views
GO Classes asked Jan 20
177 views
What is the result of the following nested list comprehension?matrix = [[1, 2], [3, 4]] result = [val for row in matrix for val in row if val % 2 == 0] print(result)$[4,2...
0 0 votes
1 1 answer
168
168 views
GO Classes asked Jan 20
168 views
Consider the following Python code snippet involving a decorator:def outer(func): def inner(*args, kwargs): return func(*args, kwargs) * 2 return inner ...