Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Modified Binary Search for Rotated Sorted Arrays

Recommended resources

Hello! Welcome to your fifth lesson in the Foundational Techniques module.

In our last lesson, we saw how to adapt binary search to find insertion points and the first/last occurrences of an element in a sorted array. The key was to modify the search condition and not stop at the first match, but to continue narrowing the search space to find the "best" possible index.

Today, we'll tackle another classic variation that builds on this adaptability. We'll learn how to search for an element in a rotated sorted array. This problem is a favorite in coding interviews because it tests your ability to reason about boundary conditions within the binary search framework. Mastering this pattern is a significant step toward your goal of interview readiness.

This lesson directly addresses the learning outcome: Solve rotated sorted array problems using a modified binary search.

1. Understanding the Rotated Sorted Array

A rotated sorted array is an array that was originally sorted in ascending order but was then "rotated" at some unknown pivot point. This means a suffix of the array was cut and moved to the beginning.

For example, if we start with the sorted array:
[0, 1, 2, 4, 5, 6, 7]

A rotation at the element 4 (index 3) would result in:
[4, 5, 6, 7, 0, 1, 2]

The array is no longer fully sorted, but it retains a crucial structure: it's composed of two individually sorted segments. A linear scan would find an element in time, but the interview constraint is almost always , which strongly hints at a modified binary search.

To get a clear visual intuition for this structure, let's start with a short video.

Search in rotated sorted array - Leetcode 33 - Python

This video from NeetCode provides an excellent graphical explanation of what a rotated sorted array is and why a modified binary search is the right tool for the job.

Watch the first 2 minutes and 30 seconds (00:00 - 02:29). Pay attention to the graph visualization, which clearly shows the two sorted portions of the array.


2. The Core Insight: One Half is Always Sorted

The key to solving this problem in time is realizing a fundamental property of rotated sorted arrays:

When you split a rotated sorted array at its midpoint, at least one of the two halves (left or right) will be perfectly sorted.

This single property allows us to adapt binary search. In each step, we can identify which half is sorted and then make an intelligent decision about where the target must lie.

Search in Rotated Sorted Array Visual Explanation
This diagram visually connects the code logic to the pointer movements. The core idea is to identify the sorted portion (left or right of `m`) and then check if the target lies within that sorted range to decide which half to discard.

Our algorithm will look like this at each step:

  1. Calculate the middle index mid.
  2. If nums[mid] is the target, we've found it. Return mid.
  3. Determine which half is sorted. A simple way to check is if nums[left] <= nums[mid]. If this is true, the left half is sorted. Otherwise, the right half must be sorted.
  4. Once the sorted half is identified, check if the target value falls within the range of that sorted half.
    • If it does, we can confidently discard the other half and continue our search in the sorted portion.
    • If it doesn't, the target must be in the other (unsorted) half, so we discard the sorted half and search there.

3. Developing the Algorithm

Let's refine the logic from the previous section. We'll use l and r for our left and right pointers.

while l <= r:
    mid = l + (r - l) // 2

    if nums[mid] == target:
        return mid

    # Case 1: The left half (from l to mid) is sorted
    if nums[l] <= nums[mid]:
        # Is the target in this sorted left half?
        if nums[l] <= target < nums[mid]:
            r = mid - 1  # Search left
        else:
            l = mid + 1  # Search right (the unsorted part)
            
    # Case 2: The right half (from mid to r) is sorted
    else:
        # Is the target in this sorted right half?
        if nums[mid] < target <= nums[r]:
            l = mid + 1  # Search right
        else:
            r = mid - 1  # Search left (the unsorted part)

return -1 # Target not found

To see this logic explained and applied step-by-step, let's return to the NeetCode video.

Search in rotated sorted array - Leetcode 33 - Python

This segment of the NeetCode video breaks down the discrete cases and then translates them directly into a Python implementation.

Watch from 02:29 to 13:21. The first part (until 06:45) explains the conditional logic in detail. The second part (until 08:56) walks through an example. The final part shows the complete Python implementation. Focus on how the if/else statements correspond to the logic we just discussed.

For a different perspective and a very detailed textual walkthrough, the following resource is also excellent.

33. Search in Rotated Sorted Array - Detailed Explanation

This article from DesignGurus provides a comprehensive step-by-step explanation with clear illustrations and code examples. It's great for reinforcing the concepts from the video.

Read the sections 'Optimized Binary Search Approach', 'Step-by-Step Walkthrough with Visual Example', and 'Common Mistakes & Edge Cases'. Pay close attention to the walkthrough example as it builds great intuition for the pointer movements.

Test your understanding!

Let's trace the first step of the algorithm on the array nums = [6, 7, 1, 2, 3, 4, 5] with target = 2.

Initial state: l = 0, r = 6.

  1. What is mid? What is nums[mid]?
  2. Is the left half (nums[l] to nums[mid]) sorted?
  3. Based on your answer, which if or else block will be executed?
  4. Where will the l and r pointers be for the next iteration?
Show answer
  1. mid = (0 + 6) // 2 = 3. nums[mid] is 2.
  2. The left half is from index 0 to 3. nums[l] = 6, nums[mid] = 2. Since 6 > 2, the left half is not sorted.
  3. The else block will be executed, because nums[l] > nums[mid]. This means the right half is sorted.
  4. The right half (nums[mid] to nums[r]) is [2, 3, 4, 5]. We check if the target is in this range: nums[mid] < target <= nums[r] -> 2 < 2 <= 5. This is false. Therefore, the target must be in the unsorted left part. We update r = mid - 1, so the new state is l = 0, r = 2.

(Note: In this specific trace, nums[mid] actually equaled the target, so the algorithm would have returned mid immediately. The trace above assumes nums[mid] != target to demonstrate the pointer-update logic.)


4. Extending the Pattern: Find Minimum Element

The core idea of identifying the sorted portion of a rotated array is a powerful pattern. It can be used to solve other related problems, like Find Minimum in Rotated Sorted Array (LeetCode 153).

The logic is similar:

  • Perform a binary search.
  • In each step, check if the middle element is in the "larger" left sorted portion or the "smaller" right sorted portion.
  • If nums[mid] is greater than or equal to nums[left], it means mid is in the left (larger values) sorted portion. Therefore, the true minimum must be to its right. So, we search right: left = mid + 1.
  • Otherwise, mid is in the right (smaller values) sorted portion. The minimum could be nums[mid] itself or an element to its left. So, we search left: right = mid - 1.

Watching a solution for this problem can help solidify the general pattern.

Find Minimum in Rotated Sorted Array - Binary Search - Leetcode 153 - Python

This NeetCode video solves 'Find Minimum in Rotated Sorted Array'. Notice how it reuses the same fundamental binary search modification: identifying which sorted section the middle element belongs to.

You can watch the sections on the logic breakdown (03:50 - 06:40), the example walkthrough (08:07 - 10:02), and the code implementation (10:10 - 12:12). Focus on the similarities in the decision-making process compared to the search problem.


Conclusion

You have now learned a powerful and frequently tested binary search pattern. By understanding the underlying structure of a rotated sorted array, you can adapt the standard algorithm to solve the problem efficiently.

Key Takeaways:

  • A rotated sorted array consists of two sorted subarrays.
  • The key insight for an solution is that at any midpoint, at least one half of the array is guaranteed to be sorted.
  • The algorithm involves identifying the sorted half and then checking if the target lies within its range to decide which half to discard.
  • This pattern of identifying a sorted subsection is versatile and can be applied to related problems like finding the minimum element.

In our next lesson, we will explore a completely different application of binary search. Instead of searching for an element within a data structure, we will learn how to search for an optimal value in a range of possible answers, a technique known as "Binary Search on the Answer Space."