Back

Search in Rotated Sorted Array

medium

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 k (e.g., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

Given the array nums after the possible rotation, 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.

Test Cases

Copy an input into the main harness and Run to verify
Input
nums = [4,5,6,7,0,1,2], target = 0
Expected Output
4
Input
nums = [4,5,6,7,0,1,2], target = 3
Expected Output
-1
Input
nums = [1], target = 0
Expected Output
-1

Constraints

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique.
  • nums is an ascending array that is possibly rotated.

Hints

Hint 1 — click to reveal

At least one half of the array is always sorted.

Hint 2 — click to reveal

Check which half is sorted, then whether the target lies inside it.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.