Video in progress

How do you search for an element in O(log n) in a sorted array that has been rotated at an unknown point ([4,5,6,7,0,1,2])?

I modify binary search: at each step, one of the two halves around mid is always sorted. I work out which one is sorted, check whether the target falls into that range, and discard the appropriate half.

📖 Answer

static int searchRotated(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]) {                    // the left half is sorted
            if (a[lo] <= target && target < a[mid]) hi = mid - 1;
            else lo = mid + 1;
        } else {                                   // the right half is sorted
            if (a[mid] < target && target <= a[hi]) lo = mid + 1;
            else hi = mid - 1;
        }
    }
    return -1;
}

The key observation: the rotation point (the "jump") can be in only one half. The other half is an ordinary sorted piece, and it's easy to compare the target against its bounds.

The = in a[lo] <= a[mid] matters: when lo == mid (a two-element range), the left half is a single element, which counts as sorted.

With duplicates ([1,1,1,3,1]), when a[lo] == a[mid] == a[hi] you can't tell which half is sorted. In that case you do lo++ and take one step, and the worst case drops to O(n). If you mention that yourself, the interviewer will rate it highly.