← DiffPush

Search in rotated sorted array

Baseline Binary Search · 1D Arrays O(log n) · O(1)

Locating a Cassette in a Wrapped Carousel

A carousel of tape cassettes is arranged in ascending order, but the whole ring was advanced by an unknown number of slots, so the sequence reads like a shifted ascending run. The retrieval arm must still find one cassette in a handful of probes. Either identify the requested cassette's slot or declare it absent.

Input: An array nums of n distinct integers, sorted ascending then rotated at an unknown pivot, and an integer target.

Output: The index of target in nums, or -1 when target is absent.

Constraints

Examples

Example 1

Input: {"nums":[4,5,6,7,0,1,2],"target":0}
Output: 4
The wrap point sits between 7 and 0, and probing halves that still respect order locates 0 at index 4.

Example 2

Input: {"nums":[4,5,6,7,0,1,2],"target":3}
Output: -1
Neither wrapped half can contain 3, so the search exhausts its space and reports -1.

Solve this in your browser →

Also on LeetCode ↗