150NeetCode 150

32.Search in Rotated Sorted Array

MediumBlind 75Binary Search ยท 5/7

Problem

An ascending array of distinct integers nums has possibly been rotated at an unknown pivot k, so it looks like [nums[k], ..., nums[n-1], nums[0], ..., nums[k-1]]. For example [0,1,2,4,5,6,7] rotated at index 3 becomes [4,5,6,7,0,1,2].

Given the rotated array and an integer target, return the index of target, or -1 if it is not in the array. The algorithm must run in O(log n) time.

Examples

Input:  nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output: 4
Explanation: 0 sits at index 4, right after the rotation point.
Input:  nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output: -1
Explanation: 3 is not in the array.
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.
  • -10^4 <= target <= 10^4

๐Ÿ’ก Key Insight

Cut a rotated sorted array at any mid and at least one of the two halves is perfectly sorted. If nums[l] <= nums[mid], the left half [l, mid] is sorted; otherwise the right half [mid, r] is. For the sorted half we can check with two comparisons whether target lies inside its range โ€” if yes, search there; if not, it must be in the other half. That keeps the classic "discard half per step" property.

Brute Force

TimeO(n).SpaceO(1).

Intuition

Ignore the structure and scan every index.

Algorithm

  1. For each i, if nums[i] == target return i.
  2. Return -1.

Visualization

nums = [4, 5, 6, 7, 0, 1, 2], target = 0
4 โœ—  5 โœ—  6 โœ—  7 โœ—  0 โœ“ โ†’ return 4

Code

java
class Solution {
    public int search(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return i;
            }
        }
        return -1;
    }
}

Complexity

  • Time: O(n).
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force O(n) O(1)
Find Pivot + Binary Search O(log n) O(1)
One-Pass Modified Binary Search O(log n) O(1)

Common Pitfalls

  • Using nums[l] < nums[mid] instead of <= โ€” when l == mid (two-element window) the left "half" is a single sorted element, and the strict check sends you into the wrong branch.
  • Getting the range bounds' strictness wrong: nums[mid] was already compared, so the tests are nums[l] <= target < nums[mid] and nums[mid] < target <= nums[r].
  • Testing whether target is in the unsorted half โ€” its endpoints do not bound its contents, so the check is meaningless.
  • In the pivot approach, forgetting that an unrotated array has pivot = 0, making the left run [0, -1] empty โ€” that case must still work (it does, since target <= nums[n-1] routes to the full array).