QuestionsDSA

Search in Rotated Sorted Array

Binary SearchMediumDSA

A sorted array was rotated at an unknown pivot. Find a target's index in O(log n), or -1.

What it tests

Adapting binary search when the array isn't globally sorted but each half still is.

Approach & answer

At each mid, one half is always sorted. Detect which (compare nums[lo] to nums[mid]). If the target lies within that sorted half's range, search it; otherwise search the other half. Same O(log n), just smarter branch selection. The rotation breaks global order but preserves it locally — that's the exploit. Use `nums[lo] <= nums[mid]` (with `<=`) to handle the two-element case where lo and mid coincide. If duplicates were allowed you'd lose the O(log n) guarantee, because nums[lo] == nums[mid] no longer tells you which half is sorted (that's the LeetCode 81 variant).

Use this technique when

Binary search on data with a twist (rotation, mountain, matrix) — figure out which half is 'well-behaved' each step.

Complexity

Time O(log n) · Space O(1)

References

js