DSA binary search learning path Level 2 This level · 5 of 7
Medium dsa binary-search

Search in Rotated Sorted Array

The 30 second answer

The array was sorted and then rotated, and I must find a target in logarithmic time. At mid, at least one half is still sorted. I check whether the target lies inside the sorted half, and I throw the other half away; if it does not, I search the unsorted half, which is itself a smaller rotated array.

Could you say this in an interview?

Problem Given an array of distinct values that was sorted in ascending order and then rotated, return the index of a target, or -1 if it is not present, in O(log n) time. Original: LeetCode 33: Search in Rotated Sorted Array.

Understanding the prompt A single mid can no longer be compared with the target in isolation, because the drop may sit on either side. Distinct values mean nums[lo] <= nums[mid] is a reliable test that the left half is sorted. The official problem forbids a linear scan.

Pattern recognition Boundary binary search on a rotated range: identify the sorted half, then decide whether the target is inside it.

Brute force A linear scan: O(n).

Optimal While lo <= hi, mid = lo + (hi - lo) / 2, and return mid on an exact hit. If nums[lo] <= nums[mid], the left half is sorted: if the target is in [nums[lo], nums[mid]), search left, otherwise right. If the left half is not sorted, the right half is, and you do the symmetric test against (nums[mid], nums[hi]].

Alternatives First find the minimum, then run ordinary binary search in the correct half. That is two logarithmic passes and is easier to explain; the one-pass version above is what interviewers often hope to see.

Java solution

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

    public static void main(String[] args) {
        System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 0)); // 4
        System.out.println(search(new int[] {4, 5, 6, 7, 0, 1, 2}, 3)); // -1
        System.out.println(search(new int[] {1}, 0));                    // -1
        System.out.println(search(new int[] {1}, 1));                    // 0
    }
}

Complexity O(log n) time, O(1) extra space.

Edge cases

  • Official samples: [4,5,6,7,0,1,2] with target 0 returns 4; with target 3 returns -1.
  • A single element, as in 1 with 0 or 1.
  • The array is not actually rotated: the left-half-is-sorted branch handles it.

Follow-ups

  • With duplicates, equal values at lo, mid and hi can force you to shrink the range by one, and the worst case becomes linear.
  • Two numbers that sum to k in a rotated sorted array is already answered on Kuchup's Zalando technical-round page, so it is not repeated here.

Tests [4,5,6,7,0,1,2] with target 0 returns 4, and with target 3 returns -1. 1 with target 0 returns -1, and with target 1 returns 0.

How to say it in the interview "At mid, one half is still sorted. I test whether the target sits inside that sorted half; if it does I search there, otherwise I search the rotated half. I still compute mid so the index sum cannot overflow. Logarithmic time."

Sources (1)
  1. LeetCode 33: Search in Rotated Sorted Arrayleetcode.com
Previous
Next