Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Search in Rotated Sorted Array

Searchingmedium

Given a rotated sorted array `nums` of distinct values, implement `search(nums, target)` returning the index of `target` or `-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

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Misjudging which half is sorted at the rotation point.

Learning resources

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

Modified binary search checks which half is ordered and narrows accordingly. O(log n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.