← Whiteboard questions

Search in Rotated Sorted Array

Find a target in a sorted array that was cut and swapped, without finding the cut

DSA, Medium, Binary Search

Which structure or algorithm, and what does it cost.

A sorted list of distinct integers was cut at some position and the two parts were swapped, so the list now starts in the middle of the sorted order and wraps around. For example, [1, 3, 4, 6, 7, 9] can become [6, 7, 9, 1, 3, 4]. The list may also be left uncut. You get this list nums and a number target. Return the position of target in nums, or -1 if it is not there. You do not know where the cut is.

Examples

Input nums = [6, 7, 9, 1, 3, 4], target = 3
Output 4
Why 3 is at position 4. The cut is between 9 and 1.
Input nums = [6, 7, 9, 1, 3, 4], target = 5
Output -1
Why 5 is not in the list, even though it lies between 4 and 6 in sorted order.
Input nums = [8], target = 8
Output 0
Why Edge case: a list with one item. The same code must handle it with no special branch.

Constraints

Your answer must contain

Target Aim for O(log n) time and O(1) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A plain binary search needs a sorted list. Look at this list: what do you notice about the order of its two parts?

Hint 2 the approach

Split the range at the middle. The cut can sit in only one of the two halves. What does that tell you about the other half?

Hint 3 the key step

One half is always sorted. Find which one by comparing its two ends. Then test whether the target lies between those ends, and keep or drop that half.

Walkthrough

Full walkthrough brute force to best

Brute force

Scan the list from the start and return the first position that holds the target. It is always right, and it costs O(n) time, which is up to 100,000 steps for one search. The task says you search many times, so a scan every time is not accepted.

Best method

The list is two sorted runs joined at the cut. At every step, at least one half around the middle is fully sorted. If the first item of the range is not larger than the middle item, the left half is sorted. Otherwise the right half is sorted. A sorted half answers one question exactly: does the target lie inside its range? If it does, keep that half. If it does not, the target can only be in the other half. Each step drops half of the range, so the cut never has to be found.

Hand trace

Run on [6, 7, 9, 1, 3, 4] with target 3. Start with lo 0 and hi 5, so mid is 2 and holds 9. The left half 6, 7, 9 is sorted and 3 is not in it, so lo becomes 3. Now lo is 3 and hi is 5, so mid is 4 and holds 3, which is the target. Return 4.

Code

def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[lo] <= nums[mid]:                 # left half lo..mid is sorted
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:                                     # right half mid..hi is sorted
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

Time and memory

O(log n) time, because each step halves the range. O(1) memory, because only three positions are kept.

Common mistakes

  • Testing "is the left half sorted" with a strict less-than. With two items the middle is the first item, and the test fails.
  • Running a plain binary search as if the whole list were sorted.
  • Testing the target against the sorted half with the wrong strictness, such as nums[lo] < target where <= is needed. A target at the end of the half is then sent to the other half.

Related problems

More Binary Search problems
Search in Rotated Sorted Array: walkthrough and solution