KatInterview

Locate a Value in a Cyclically Shifted Ascending List

Heaps, Sorting & SearchAuto-graded · 27 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysrotated-array

Last updated

Search a cyclically shifted strictly increasing list of distinct integers for a value in O(log n), returning its index or -1, including unshifted and single-element cases.

Locate a Value in a Cyclically Shifted Ascending List

A list of distinct integers started out in strictly ascending order. It was then cyclically shifted: for some shift amount s with 0 <= s < n, the first s elements were moved to the end while keeping their relative order. In other words, the ascending list [b0, b1, ..., b(n-1)] turned into [bs, b(s+1), ..., b(n-1), b0, ..., b(s-1)]. A shift of s = 0 leaves the list unchanged.

You are given the shifted list nums and an integer target. Return the position of target within nums, or -1 if target does not appear.

Your solution should run in time logarithmic in the length of the list.

Function

Implement search_rotated(nums, target), which takes the shifted list and the value to find and returns a single integer.

Rules

  • Positions are 0-based.
  • All values in nums are distinct, so at most one position matches.
  • nums is guaranteed to be a cyclic shift of a strictly ascending list (possibly with shift 0).
  • Return -1 when target is not in nums.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • All elements of nums are distinct.

Examples

Example 1

Input: search_rotated([15, 18, 22, 3, 7, 11], 7)

Output: 4

Example 2

Input: search_rotated([15, 18, 22, 3, 7, 11], 20)

Output: -1

Example 3

Input: search_rotated([1, 4, 9, 12], 12)

Output: 3

Hints

Hint 1

Cut the list at any middle index. The point where values drop can only be on one side, so at least one of the two sides is entirely in ascending order.

Hint 2

Compare the value at the left end of the current window with the value at the middle to decide which side is the ascending one. Use <= so a window where the middle equals the left end is handled correctly.

Hint 3

Once you know the ascending side, check whether target lies between its end values. If yes, keep that side; otherwise discard it and keep the other side. Make sure the endpoint checks are inclusive where the endpoint has not already been ruled out.