Search in Rotated Sorted Array

Mediumbinary searchMetaAmazonGoogleMicrosoft

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 (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]].


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.

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
Input:nums = [1], target = 0
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

At any point, one half of the array is always sorted.

Hint 2

Check if the target lies in the sorted half. If yes, search there. Otherwise, search the other half.

Hint 3

Use standard binary search with an extra conditional to determine which half is sorted.

Algorithm Complexity

Official asymptotic Big-O runtime and auxiliary memory analysis

Logarithmic
Algorithmic Approach

Modified binary search. At each step, determine which half is sorted. If the target is in the sorted range, search there. Otherwise, search the other half.

Time ComplexityO(log n)
Why:

Determines which half of the array is normally sorted and discards half the search space at each comparison.

Space ComplexityO(1)
Why:

Operates in-place with constant auxiliary pointers (left, right, mid).

Big-O Growth CurveExcellent (O(log N))
Execution time grows slowly by repeatedly halving the search space.

šŸŒ Real-World Use Cases

DatabasesCircular buffer search

Searching for a value in a circular log buffer where entries wrap around — the same rotated binary search logic applies.

šŸ” Dry Run

Solutionā± O(log n) | šŸ’¾ O(1)
Line2
left=0number
right=6number
target=0number

Search for 0 in [4,5,6,7,0,1,2]. Initialize left=0, right=6.