← Whiteboard questions

Search in a rotated sorted array

DSA, Medium

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

Search in a rotated sorted array · OpsKarma