Binary Search · Pattern 4 of 8

Rotated sorted arrays

A sorted array cut and swapped. At every mid, one half is still sorted: find out which, then decide whether the answer can be in it.

3 variations · 5 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Sorted, then rotated by an unknown amount
  • Find the minimum, the rotation count or a target in O(log n)
  • Duplicates allowed (the harder version)

The template

Rotated Array
int search(int[] a, int target) {
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) return mid;
        if (a[lo] <= a[mid]) {                                // left half is sorted
            if (a[lo] <= target && target < a[mid]) hi = mid - 1;
            else lo = mid + 1;
        } else {                                              // right half is sorted
            if (a[mid] < target && target <= a[hi]) lo = mid + 1;
            else hi = mid - 1;
        }
    }
    return -1;
}

// minimum: compare with the right end
int findMin(int[] a) {
    int lo = 0, hi = a.length - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] > a[hi]) lo = mid + 1;   // the drop is right of mid
        else hi = mid;                      // mid could be the minimum
    }
    return a[lo];
}

The variations

  1. 1Find the rotation point

    The minimum is where the order breaks. If a[mid] > a[hi] the break is to the right; otherwise mid is at or after it. Its index is also the rotation count.

  2. 2Search for a target

    One half around mid is always sorted. If the target lies inside that sorted half's range go there, otherwise go to the other half.

  3. 3With duplicates

    When the ends equal mid you cannot tell which half is sorted. Drop one end (hi--) and carry on. Interviewers want you to say why this is O(n) in the worst case.

Mistakes to avoid

  • Using < instead of <= in a[lo] <= a[mid]: with two elements left, lo == mid and the left half is sorted.
  • Comparing a[mid] with a[lo] to find the minimum: it fails when the array is not rotated. Compare with a[hi].
  • With duplicates, a[mid] == a[hi] tells you nothing: shrink with hi-- (worst case O(n)).
Next: Searching a sorted 2D matrix →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.