AlgoInsight

DSA problem

Search in Rotated Sorted Array

MediumBinary SearchPattern: Binary Searchtop75FreeAmazonMicrosoftGoogleFacebookAppleBloomberg

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 (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], ..., 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. You must write an algorithm with O(log n) runtime complexity.

The crucial observation is that, for any midpoint mid, at least one of the two halves [lo, mid] or [mid, hi] is fully sorted (not crossed by the rotation pivot). Comparing nums[lo] with nums[mid] reveals which: if nums[lo] <= nums[mid], the left half is sorted; otherwise the right half is.

Once you know which half is sorted, you can decide where target could live in O(1): if it is in the sorted half's range, discard the other half; otherwise discard the sorted half. This still halves the window per iteration, preserving O(log n) running time. The whole algorithm is just the classic binary search with an extra branch to handle which side is sorted.

Edge cases worth checking are an unrotated array (k = 0), a fully-rotated-back array, single element inputs, and the target equaling nums[lo] or nums[mid]. Use <= carefully when checking whether a half is sorted; with distinct values nums[lo] <= nums[mid] is the right inequality.

Examples

Example 1
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Explanation: The pivot is between 7 and 0. At mid = 3 (value 7), the left half is sorted; 0 is not in [4, 7] so we search the right half and find 0 at index 4.
Example 2
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Explanation: Following the same logic, 3 falls into none of the half ranges as the window shrinks, and the search returns -1.
Example 3
Input: nums = [1], target = 0
Output: -1
Explanation: A single-element array cannot contain 0, so the function returns -1 immediately.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searcharrayrotated-array

Browse all DSA problems