v9.1.1
Menu

Search in Rotated Sorted Array

mediumPROSearch & SortGoogle DSA

Given a rotated sorted array nums (with distinct values) and a target, return the index of target or -1 if not found.

You must achieve O(log n) time complexity.

Example

Input
4,5,6,7,0,1,2
0
Output
4
Reasoning
  • Input: nums =[4,5,6,7,0,1,2]= [4, 5, 6, 7, 0, 1, 2] is the sorted list [0,1,2,4,5,6,7][0, 1, 2, 4, 5, 6, 7] rotated to start at 44; target =0= 0. Indices run 00 to 66.
  • The rotation leaves two ascending runs: [4,5,6,7][4, 5, 6, 7] at indices 00 to 33, then [0,1,2][0, 1, 2] at indices 44 to 66.
  • Every value in the first run is at least 44 (its first element), and every value in the second run is at most 22 (the last element of the array). Since 0<40 < 4, the target cannot be in the first run; it can only be in the second.
  • The second run begins with the smallest value of the whole array, 00, at index 44. That matches the target, so the output is 4.
  • Notice that for target =3= 3, 3<43 < 4 rules out the first run and 3>23 > 2 rules out the second, so the answer would be −1-1. The O(log⁡n)O(\log n) bound means reaching such conclusions without checking every element.

Constraints

  • 1 <= len(nums) <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values are unique
  • nums was rotated at some pivot

More from Google DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.