KatInterview

Find a Value in a Shifted Sorted Array

Heaps, Sorting & SearchAuto-graded · 27 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysdivide-and-conquer

Last updated

Tests whether a candidate can run a single-pass binary search on a sorted array that has been cyclically shifted by an unknown offset.

Problem

You have a list of integers that was originally sorted in strictly increasing order with no repeated values. At some point, the list was "shifted" — a suffix of the array was moved to the front. For example, [0, 1, 2, 4, 5, 6, 7] might become [4, 5, 6, 7, 0, 1, 2] after a shift.

Given this shifted list and a target value, return the 0-based index of the target if it appears in the list, or -1 if it does not.

Your solution must run in O(log n) time using a single binary-search pass — you may not first locate the shift point and then do a separate search. The input list must not be modified.

How to Approach It

At any midpoint you pick, one of the two halves is always an unbroken ascending run. Use the endpoints of that sorted half to decide whether the target could live there, and shrink the window accordingly.

Constraints

  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • All values in arr are distinct.
  • The array may or may not have been shifted (an unshifted array is a valid input).
  • -10^9 <= target <= 10^9

Examples

Example 1

Input: find_in_shifted_array([4, 5, 6, 7, 0, 1, 2], 0)

Output: 4

Example 2

Input: find_in_shifted_array([4, 5, 6, 7, 0, 1, 2], 3)

Output: -1

Example 3

Input: find_in_shifted_array([1], 0)

Output: -1

Hints

Hint 1

Split the window at mid. One of [left, mid] or [mid, right] must be a clean ascending run — figure out which one by comparing arr[left] with arr[mid].

Hint 2

Once you know which half is sorted, its two endpoints tell you exactly whether the target can be inside it. If it can, search there; otherwise search the other half.

Hint 3

Be careful with the comparison operator when checking whether the left half is sorted. When the window shrinks to two elements, left == mid, so you need <= rather than < to avoid misclassifying that case.