Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Search in Rotated Sorted Array

Searchingmedium

A sorted array of **distinct** integers has been rotated at an unknown pivot (e.g. `[0,1,2,4,5,6,7]` might become `[4,5,6,7,0,1,2]`). Implement `search(nums, target)` returning the index of `target`, or `-1` if it is absent. Aim for O(log n).

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

Sample tests

Input: search([4,5,6,7,0,1,2], 0)
Output: 4
Input: search([4,5,6,7,0,1,2], 3)
Output: -1

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Using `<` instead of `<=` when testing `nums[lo] <= nums[mid]` mishandles the two-element case.

Learning resources

  • Wikipedia: Binary search algorithm
Approach & explanation (try first)

Even after rotation, a binary-search step always has at least one sorted half. Determine which half is sorted, test whether the target falls inside its range, and discard the other half. O(log n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.