The Runtime Theory
mediumleetcode#binary-search#array

Search in Rotated Sorted Array

Search a target in a rotated sorted array by detecting which half is sorted at each midpoint and recursing into the matching half.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[4,5,6,7,0,1,2], 0

out4

in[4,5,6,7,0,1,2], 3

out-1

in[1], 0

out-1

The machine must find a target in an array that was sorted, then rotated at an unknown pivot — values are distinct. A normal binary search fails because the array is not monotonic, but at any midpoint one of the two halves is fully sorted. The trick: detect which half is sorted, check whether the target lies inside its range, and narrow into the half that must contain the target.

python
def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[lo] <= nums[mid]:          # left half is sorted
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:                              # right half is sorted
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

Steps: (1) find the sorted half via nums[lo] <= nums[mid], (2) test membership in that half, (3) narrow accordingly. Each iteration still discards half the window, so the log bound holds.

Time is O(log n). Space is O(1).

Trickiest edge case: a fully rotated array — [3,4,5,1,2] — where both range checks must be inclusive on exactly one end. The <= in the sorted-half test is deliberate: when lo == mid, the left half is a single element. Distinct values are guaranteed, so there is no duplicate ambiguity.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.