Skip to the solution
MediumDSA7 min read

How do you search in a rotated sorted array?

891 views

The problem

Question presented to candidate: "You are given a sorted array of distinct integers that has been rotated at an unknown point, like [4, 5, 6, 7, 0, 1, 2], and a target. Return its index or -1, in O(log n) time. Please code it in Python."

What a strong answer should cover:

  • The key insight: at any midpoint at least one half is sorted, and nums[lo] <= nums[mid] tells you which.
  • Correct range checks: search the sorted half only if the target lies within its end values, otherwise the other half.
  • O(log n) time and O(1) space, plus the two-pass alternative (find the rotation point, then binary search one run).
  • Edge cases: not rotated, one or two elements (the <=), empty array, target absent.
  • The duplicates follow-up: shrink both ends when nums[lo] == nums[mid] == nums[hi]; worst case O(n).
  • Python specifics: chained comparisons (nums[lo] <= target < nums[mid]) for the range test, // for the midpoint, and why nums.index is the O(n) brute force.

Clarifying questions expected:

  • Are all values distinct?
  • Should I return the index or just whether it exists?
  • Can the array be empty or not rotated at all?

Code / implementation expected: Yes โ€” a one-pass O(log n) Python solution, tested on edge cases.

  • binary-search
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne-pass search, checked against every rotation
PythonRotation point, two-pass search, and duplicates

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 57 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the next greater element for every item (Daily Temperatures)?

Continue