Polski

Search in a rotated array

Someone "turned" a sorted array at an unknown point. Find an element in O(log n) – binary search that recognises the sorted half at every step.

medium · typescript · javascript · python · csharp · java · go · 20 XP

A ring buffer of event IDs stores them in ascending order, but once full it starts from the beginning again – so memory holds a sorted array rotated at an unknown point, e.g. [40, 50, 60, 70, 10, 20, 30]. Find the position of the event with a given ID.

Task

The function gets an array nums of distinct integers (sorted ascending, then rotated by any number of positions, possibly zero) and a value target. Return the index of target in nums, or -1 when it is absent.

The solution has to run in O(log n) time – the tests count element reads (in JS/TS and Python the array is sometimes replaced by an object supporting only length and indexing) and run a hundred thousand searches in an array of a million elements.

Signatures: searchRotated(nums, target) (JS/TS), search_rotated(nums, target) (Python), Solution.SearchRotated (C#), Solution.searchRotated (Java), SearchRotated (Go).

Examples

numstargetResult
[4, 5, 6, 7, 0, 1, 2]04
[4, 5, 6, 7, 0, 1, 2]3-1
[1, 2, 3, 4, 5]43 – no rotation
[3, 1]11
[]7-1

Constraints

  • 0 ≤ n ≤ 1,000,000, distinct values in the 32-bit int range.

Expected complexity

O(log n) time, O(1) memory.