Skip to content
BytePatterns

Target in a Rotated Sorted List

MediumSearching#binary-search#rotated-array~20m

Problem

A list of distinct integers was sorted in ascending order and then rotated at an unknown point, so [0, 1, 2, 4, 5, 6, 7] might have become [4, 5, 6, 7, 0, 1, 2]. Given the rotated list and a target, return the index of the target, or -1 if it is not there. The search must run in O(log n) time.

Examples

Input:  nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output: 4
Input:  nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output: -1
Why:    3 would sit between 2 and 4, and neither side of the rotation holds it
Input:  nums = [3, 1], target = 1
Output: 1
Why:    edge case, with two values the middle index is the first one and the left half has one element

Hints

0 / 3

Stuck on the idea rather than the code? Search in Rotated Array covers it.