Search in Rotated Sorted Array

MediumBinary searchLeetCode 33 ↗World 2-24
0:00 / 0:00

A sorted list was rotated, yet binary search still works: one half is always in order, so check if the target sits there and drop the other.

▼

The problem

LeetCode 33 (Medium). A sorted array of distinct integers was rotated at an unknown pivot (for example [0,1,2,4,5,6,7] became [4,5,6,7,0,1,2]). Given target, return its index, or −1 if it isn't there, in O(log n).

Examples (LeetCode's, the ones animated): nums = [4,5,6,7,0,1,2], target = 0 → 4 (mids 3, 5, 4: three probes); target = 3 → −1.

TRY IT ON LEETCODE ▶

The solution

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]:
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

Transcript

Search in Rotated Sorted Array. A sorted list of distinct numbers was turned, like a combination dial. Given a target, return its index, or minus one if it's missing, in log n time.

Take four, five, six, seven, zero, one, two. Target zero sits at index four. Target three isn't there, so minus one.

Checking every number is order n. And plain binary search breaks: the middle is seven, zero is smaller, so it searches left, and misses.

The fix: split at the middle, and one half is always sorted, because the turn can only break one side. If the left end is at most the middle, the left half is sorted; if not, the right half is. Is the target inside the sorted half's range? Search there. Otherwise, search the other half.

Let's find zero. Mid is index three: seven. Four to seven is sorted, and zero isn't in it, so low jumps past mid. Now mid is five: one. Zero to one is sorted and holds zero, so high drops below mid. Mid is four: zero. Found at index four, in three steps.

Now turn the dial further: six, seven, zero, one, two, four, five. Find zero again. Mid is one, and the left end, six, is bigger, so the right half is sorted: one to five. No zero there, so go left. Mid is seven: six to seven is sorted, no zero, so go right. Mid is zero, at index two.

In code, keep low and high. Take mid; if it's the target, return it. If the left half is sorted and the target falls inside, move high below mid; else move low past mid. Otherwise the right half is sorted, so mirror the test. When the range empties, return minus one.

Every step halves the range, so it's order log n time, and with just three pointers, order one space.

Find the sorted half, test the target, halve again. That's Search in Rotated Sorted Array.