Divide & Conquer · Search

Search in Rotated Array Visualizer

What is Search in a Rotated Array

A sorted array of distinct values was rotated, so it looks like two increasing runs. Return the index of target, or -1. One half of the current window is still sorted. Keep the half that could contain the target.

4 5 6 7 0 1 2
target 0
4

Approach

The array was sorted, then rotated, so one of the two halves around the middle is still sorted. Compare the target with that sorted half and throw the other half away.

Left half is sortedThat is true when a[lo] <= a[mid]. If the target sits between a[lo] and a[mid], keep the left half. Otherwise keep the right.
Right half is sortedOtherwise the right side is the increasing run. Keep it only when the target sits between a[mid] and a[hi].

Values are distinct, so a match at mid is the only answer. If the window empties, the target is missing and the answer is -1.

Interactive solution

Which half is sorted, then which half can hold the target
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target: return mid
if a[lo] <= a[mid]:
if target is inside the left half: hi = mid - 1
else: lo = mid + 1
else:
if target is inside the right half: lo = mid + 1
else: hi = mid - 1
return -1
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(log n)One comparison chooses a half.
MemoryO(1)Only lo, hi, and mid are stored.

Implementation

def search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[lo] <= a[mid]:
            if a[lo] <= target < a[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if a[mid] < target <= a[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1