DSA Series Day 27 Search in Rotated Sorted Array in Java, Python and Rust

DSA Series Day 27: Search in Rotated Sorted Array in Java, Python and Rust

Search in Rotated Sorted Array – Day 27 (paste-ready)

Welcome to Day 27 of the Tekraze DSA series. Yesterday we found the smallest value in a rotated sorted array. Today we take the next step and look for any value inside that same kind of array. Search in Rotated Sorted Array is LeetCode 33, and it shows up in interviews all the time because it checks whether you really understand binary search or just remember the template.

Array 4, 5, 6, 7, 0, 1, 2 split by the pivot into two sorted runs, illustrating Search in Rotated Sorted Array on LeetCode 33
Search in Rotated Sorted Array: two sorted runs joined at a pivot.

What is the Search in Rotated Sorted Array problem?

You get an array nums of unique integers. It was sorted in ascending order and then rotated at some unknown pivot, so [0, 1, 2, 4, 5, 6, 7] might become [4, 5, 6, 7, 0, 1, 2]. You also get a target. Return the index of the target if it is in the array, or -1 if it is not. Your solution has to run in O(log n) time.

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

How should you think about it in plain words?

Think of the rotated array as two sorted staircases joined together. When you pick any middle point, at least one side of it is a clean sorted run with no drop inside. That is the whole trick. You cannot tell right away where the target is, but you can always tell which half is sorted.

Once you know a half is sorted, checking whether the target lives there is easy. You just look at its first and last values. If the target falls between them, go into that half. If it does not, the target can only be in the other half. Every step still throws away half of the array, so it is still binary search, just with one extra question per step.

Rotated array with left, mid and right pointers where the left half 4, 5, 6, 7 is highlighted as the sorted half
At least one side of the middle point is always a clean sorted run.

What does the brute force approach look like?

Walk through the array and return the index the moment you see the target.

def search_brute(nums, target):
    for i, x in enumerate(nums):
        if x == target:
            return i
    return -1

This takes O(n) time and O(1) space. It always works, but it ignores the sorted structure and the problem asks for O(log n), so an interviewer will push you for something better.

Comparison of a linear scan needing up to 1,000,000 checks against modified binary search needing about 20 checks
O(n) linear scan versus O(log n) modified binary search on 1,000,000 numbers.

How do we get the optimal solution?

Keep left = 0 and right = n – 1 and loop while left <= right. Take mid. If nums[mid] is the target, you are done. Otherwise ask which half is sorted. If nums[left] <= nums[mid], the left half is sorted. Check whether the target sits in [nums[left], nums[mid]). If yes, move right = mid – 1, else move left = mid + 1. If the left half is not sorted, the right half must be. Check whether the target sits in (nums[mid], nums[right]]. If yes, move left = mid + 1, else move right = mid – 1.

Let us walk through [4, 5, 6, 7, 0, 1, 2] with target 0. Left is 0 and right is 6, so mid is 3 with value 7. The left half from 4 to 7 is sorted, and 0 is not between 4 and 7, so left becomes 4. Now mid is 5 with value 1. The left part from 0 to 1 is sorted and 0 falls inside it, so right becomes 4. Mid is 4 with value 0, which is the target, so the answer is index 4.

Step by step walkthrough of searching for target 0 in the rotated array 4, 5, 6, 7, 0, 1, 2, ending at index 4
Walkthrough for target 0: left moves to 4, right moves to 4, and mid lands on the answer.

Time is O(log n) because each step cuts the search range in half. Space is O(1) because we only track a few indexes. If you want a refresher on why halving beats a full scan so easily, read our Big O helper post on time and space complexity, and keep the data structures cheat sheet open for a quick look at how arrays and searching fit together.

Java solution

public class Solution {
    // Binary search in a rotated sorted array of unique values
    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;
            if (nums[left] <= nums[mid]) {          // left half is sorted
                if (nums[left] <= target && target < nums[mid]) right = mid - 1;
                else left = mid + 1;
            } else {                                // right half is sorted
                if (nums[mid] < target && target <= nums[right]) left = mid + 1;
                else right = mid - 1;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        int[][] tests = {{4, 5, 6, 7, 0, 1, 2}, {4, 5, 6, 7, 0, 1, 2}, {1}, {1}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {3, 1}, {5, 1, 3}, {6, 7, 1, 2, 3, 4, 5}};
        int[] targets = {0, 3, 1, 0, 4, 9, 1, 5, 7};
        int[] expected = {4, -1, 0, -1, 3, -1, 1, 0, 1};
        boolean ok = true;
        for (int i = 0; i < tests.length; i++) {
            int got = search(tests[i], targets[i]);
            System.out.println("Test " + (i + 1) + ": " + got + (got == expected[i] ? " PASS" : " FAIL"));
            ok &= got == expected[i];
        }
        System.out.println(ok ? "ALL PASSED" : "SOME FAILED");
    }
}

Writing left + (right – left) / 2 keeps the middle index safe from int overflow on very large arrays.

Python solution

def search(nums, target):
    """Binary search in a rotated sorted array of unique values."""
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        if nums[left] <= nums[mid]:          # left half is sorted
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        else:                                # right half is sorted
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1
    return -1
if __name__ == "__main__":
    tests = [([4, 5, 6, 7, 0, 1, 2], 0, 4), ([4, 5, 6, 7, 0, 1, 2], 3, -1),
             ([1], 1, 0), ([1], 0, -1), ([1, 2, 3, 4, 5], 4, 3),
             ([1, 2, 3, 4, 5], 9, -1), ([3, 1], 1, 1), ([5, 1, 3], 5, 0),
             ([6, 7, 1, 2, 3, 4, 5], 7, 1)]
    ok = True
    for i, (nums, target, want) in enumerate(tests, 1):
        got = search(nums, target)
        print(f"Test {i}: {got} {'PASS' if got == want else 'FAIL'}")
        ok &= got == want
    print("ALL PASSED" if ok else "SOME FAILED")

Python lets you chain comparisons like nums[left] <= target < nums[mid], which reads almost exactly like the range check in plain words.

Rust solution

The Rust version keeps left and right as i64. Because we write right = mid – 1, an unsigned index could drop below zero and panic, so signed indexes are the safe choice here.

// Binary search in a rotated sorted array of unique values
fn search(nums: &[i32], target: i32) -> i32 {
    let (mut left, mut right) = (0i64, nums.len() as i64 - 1);
    while left <= right {
        let mid = left + (right - left) / 2;
        let (l, m, r) = (nums[left as usize], nums[mid as usize], nums[right as usize]);
        if m == target {
            return mid as i32;
        }
        if l <= m {
            // left half is sorted
            if l <= target && target < m { right = mid - 1; } else { left = mid + 1; }
        } else {
            // right half is sorted
            if m < target && target <= r { left = mid + 1; } else { right = mid - 1; }
        }
    }
    -1
}
fn main() {
    let tests: Vec<(Vec<i32>, i32, i32)> = vec![
        (vec![4, 5, 6, 7, 0, 1, 2], 0, 4),
        (vec![4, 5, 6, 7, 0, 1, 2], 3, -1),
        (vec![1], 1, 0),
        (vec![1], 0, -1),
        (vec![1, 2, 3, 4, 5], 4, 3),
        (vec![1, 2, 3, 4, 5], 9, -1),
        (vec![3, 1], 1, 1),
        (vec![5, 1, 3], 5, 0),
        (vec![6, 7, 1, 2, 3, 4, 5], 7, 1),
    ];
    let mut ok = true;
    for (i, (nums, target, want)) in tests.iter().enumerate() {
        let got = search(nums, *target);
        println!("Test {}: {} {}", i + 1, got, if got == *want { "PASS" } else { "FAIL" });
        ok &= got == *want;
    }
    println!("{}", if ok { "ALL PASSED" } else { "SOME FAILED" });
}

All three programs ran nine sample cases, including the two LeetCode examples, a single element where the target is present and missing, an array with no rotation, a target that is not in the array at all, the two element case [3, 1], and targets sitting on the first element and right after the pivot. Every check passed in Java, Python and Rust.

What are the tips and tricks for an easy solution?

Spot the pattern. Sorted plus rotated plus a demand for O(log n) is a loud signal for modified binary search.

Ask one question per step. Which half is sorted? Once you know that, the rest is a simple range check.

Use less than or equal in the sorted check. Write nums[left] <= nums[mid]. When left and mid are the same index, that one element counts as a sorted half, and a strict less than breaks the two element cases.

Keep the bounds half open. Check nums[left] <= target < nums[mid] on the left and nums[mid] < target <= nums[right] on the right. Mid has already been checked, so it never needs to be included.

Shortcut idea. You can also find the pivot first with the find minimum trick, comparing mid with the right end, and then run a normal binary search on the correct half. It is two passes but each one is very simple, which some people find easier to get right under pressure.

Edge cases. A single element, an array with no rotation, a target that is missing, a target at index 0 or at the last index, and two elements like [3, 1].

Interview tip. Say the sentence one half is always sorted out loud before you code. It shows the interviewer you understand why the algorithm works, not just how.

What are the common mistakes people make?

Two element array 3 and 1 showing that nums[left] <= nums[mid] works while a strict less than check picks the wrong half
The two element case [3, 1] is why the sorted check uses less than or equal.
  • Using nums[left] < nums[mid] instead of <=, which picks the wrong half when left equals mid.
  • Getting the range checks off by one, for example using target <= nums[mid] or forgetting that the right range includes nums[right].
  • Comparing the target only with nums[mid] as in plain binary search, which fails as soon as the array is rotated.
  • Using unsigned indexes in Rust or C++ with right = mid – 1, which underflows when mid is 0.
  • Running this exact code on arrays with duplicates. With equal values you cannot always tell which half is sorted, so you need to shrink both ends and the worst case becomes O(n).

Where is this pattern used in the real world?

Rotated sorted data appears whenever a sorted sequence wraps around. Circular log buffers and ring buffers store records in time order but start writing again at the beginning when they fill up, so finding the record for a given timestamp is exactly this search. Fixed size time series stores used for metrics and monitoring work the same way. Consistent hashing rings in distributed caches and databases keep nodes sorted on a circle, and lookups search that ring for a position. Even sorted lists that are paged or sharded with a moving start point, like a rolling window of daily partitions, need the same idea of finding the sorted part first and then searching inside it.

Circular buffer of timestamps t1 to t8 drawn as a ring next to the rotated sorted array 5, 6, 7, 8, 1, 2, 3, 4
A ring buffer stores sorted records, but the start sits in the middle of the array.

Which earlier posts in the series should you read?

Start with Day 1, Two Sum for hash map basics and Day 2, Best Time to Buy and Sell Stock for tracking a running value. Day 3, Contains Duplicate, Day 4, Valid Anagram and Day 5, Group Anagrams build the counting toolkit, Day 6, Valid Palindrome, Day 7, Two Sum II, Day 8, 3Sum and Day 9, Container With Most Water cover two pointers, and Day 10, Longest Substring Without Repeating Characters, Day 11, Longest Repeating Character Replacement and Day 12, Minimum Window Substring walk through the sliding window section. Day 13, Valid Parentheses, Day 14, Min Stack, Day 15, Evaluate Reverse Polish Notation and Day 16, Daily Temperatures cover the stack chapter, Day 17, Implement Queue using Stacks shows how two stacks make a queue, and Day 18, Reverse Linked List, Day 19, Merge Two Sorted Lists, Day 20, Linked List Cycle and Day 21, Remove Nth Node From End of List cover the linked list chapter. Keep our data structures cheat sheet handy for a quick refresher on arrays and searching.

Frequently asked questions

What is the Search in Rotated Sorted Array problem?

You get a sorted array of unique numbers that has been rotated at an unknown pivot, plus a target. You must return the index of the target, or -1 if it is missing, in O(log n) time.

How does binary search work on a rotated sorted array?

At every step at least one half around the middle is sorted. You find that sorted half, check whether the target falls inside its range, and then keep only the half that can contain the target.

What is the time complexity of Search in Rotated Sorted Array?

The modified binary search runs in O(log n) time and uses O(1) extra space. A simple linear scan takes O(n) time.

What changes if the rotated array has duplicates?

When nums[left], nums[mid] and nums[right] are equal you cannot tell which half is sorted, so you move both ends inward by one. It still finds the target, but the worst case becomes O(n). This is LeetCode 81, Search in Rotated Sorted Array II.

Which problems are similar to Search in Rotated Sorted Array?

Find Minimum in Rotated Sorted Array, Search in Rotated Sorted Array II, Find Peak Element and Search a 2D Matrix all use a modified binary search that decides which half to keep at each step.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×