binary-search · Problem 3 of 3

Search in Rotated Sorted Array

medium
Amazon logoAmazon
Google logoGoogle
Meta logoMeta
Microsoft logoMicrosoft
Apple logoApple

There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index.

Given the array nums and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

search([4, 5, 6, 7, 0, 1, 2], 0) -> 4
search([4, 5, 6, 7, 0, 1, 2], 3) -> -1
search([1], 0)                   -> -1

Your solution

Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.

Running is free — Submit is what records it. Or press ⌘↩

Tests

5 cases, 1 hidden
calltypeexpectedresult
search([4,5,6,7,0,1,2], 0)target in right sorted half4
search([4,5,6,7,0,1,2], 3)target not present-1
search([1], 0)single element not found-1
search([1], 1)single element found0
withheldhiddenwithheld

Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.

Complexity

target time
O(log n)
target space
O(1)

Halves the search space at each iteration using modified binary search boundaries.

Hints

Stuck? Hints open one at a time, each giving a little more away.

3 hints left