Hello! Welcome to our next lesson.
In our last session, we explored a powerful application of binary search called "Binary Search on the Answer Space," which you used to solve complex optimization problems like "Koko Eating Bananas" and "Allocate Books." You learned that as long as a problem has a monotonic property, you can use binary search to efficiently find an optimal solution.
Today, we'll return to applying binary search on arrays, but with a fascinating twist. We'll tackle a classic problem frequently asked in technical interviews: searching for an element in a rotated sorted array. You will learn how to adapt the core logic of binary search to handle this specific structure, where the array is almost sorted, but not quite. This will test and deepen your understanding of how binary search fundamentally works.
1. What is a Rotated Sorted Array?
Imagine you have a perfectly sorted array, like [0, 1, 2, 4, 5, 6, 7]. If you "rotate" it at a pivot point, you might get an array like [4, 5, 6, 7, 0, 1, 2].

A standard binary search won't work here. Why? Because the core assumption of binary search—if target < arr[mid], then the target must be in the left half—is no longer true. In our example [4, 5, 6, 7, 0, 1, 2], the midpoint is 7. If our target is 0, it's less than 7, but it lies in the right half of the array!
To understand the problem setup more formally, please watch the first few minutes of this video.
Search in Rotated Sorted Array (LeetCode 33) | FREE DSA Course in JAVA | Lecture 55
This video from TAP ACADEMY introduces the 'Search in Rotated Sorted Array' problem, clarifying what a rotated array is and what our goal is.
Watch from the beginning until 03:00. This will give you a clear definition of the problem and show a few examples of rotation.
2. The Modified Binary Search Algorithm
Since a brute-force linear search (O(n)) is too slow for interview standards, we need a solution with O(log n) time complexity. This points us back to binary search. The key is to modify it.
The most crucial observation is this: At any given mid point, one half of the array (from low to mid, or from mid to high) will always be perfectly sorted.
Our strategy will be:
- Find the
midelement. - Identify which of the two halves is sorted.
- Check if our
targetlies within the range of that sorted half.- If yes, we search within that sorted half by moving our
loworhighpointer. - If no, the target must be in the other, unsorted half, so we search there instead.
- If yes, we search within that sorted half by moving our
This logic ensures that with every step, we correctly discard half of the remaining elements.
Let's watch a detailed explanation of how to implement this logic.
Search in Rotated Sorted Array (LeetCode 33) | FREE DSA Course in JAVA | Lecture 55
The same video provides an excellent, step-by-step logical breakdown of this modified binary search. The presenter clearly explains how to identify the sorted portion and make the correct decision at each step.
Watch from 03:00 to 15:01. Pay close attention to the conditions used to identify the sorted half (arr[low] <= arr[mid]) and the subsequent checks to see if the target lies within that half.
The Logic in a Nutshell:
Let's say you're inside your while (low <= high) loop:
- Calculate
mid. Ifnums[mid] == target, you've found it. Returnmid. - Check if the left half
[low...mid]is sorted. This is true ifnums[low] <= nums[mid].- If it is sorted, ask: Is the
targetwithin this sorted range? (i.e.,nums[low] <= target && target < nums[mid]).- If yes, the target must be in the left half. So,
high = mid - 1. - If no, the target must be in the right half. So,
low = mid + 1.
- If yes, the target must be in the left half. So,
- If it is sorted, ask: Is the
- If the left half is not sorted, then the right half
[mid...high]must be sorted.- Ask: Is the
targetwithin this sorted right half? (i.e.,nums[mid] < target && target <= nums[high]).- If yes, the target must be in the right half. So,
low = mid + 1. - If no, the target must be in the left half. So,
high = mid - 1.
- If yes, the target must be in the right half. So,
- Ask: Is the
Test your understanding!
Given the array nums = [7, 8, 9, 1, 2, 3, 4, 5, 6] and target = 8.
Initially, low = 0 (nums[low]=7), high = 8 (nums[high]=6). mid will be 4 (nums[mid]=2).
- Is the left half
[7, 8, 9, 1, 2]sorted? - Based on your answer, where would you continue the search?
Show answer
- The left half is not sorted because
nums[low](7) is greater thannums[mid](2). - This means the right half
[2, 3, 4, 5, 6]must be sorted. Our target, 8, is not in the range[2, 6]. Therefore, we must continue our search in the unsorted left half. The next search range will below = 0,high = mid - 1 = 3.
3. Implementation in Java
Now that you understand the logic, let's look at how it translates into a clean, iterative Java implementation. This is the kind of code you would be expected to write in an interview setting.
Mastering Binary Search: Find Elements in a Rotated Array
The following resource provides a concise, iterative Java solution for this problem. It's a great reference for a production-quality implementation.
Please read the 'Java Implementation' section. As you read the code, try to connect each 'if/else' block to the logic we just discussed: identifying the sorted half and then deciding whether the target is in that half or the other.
The code you just reviewed has a time complexity of O(log n) because it halves the search space at each iteration. The space complexity is O(1) because we are only using a few variables to store pointers (low, high, mid) without using any extra data structures that scale with the input size.
4. What About Duplicates?
A common follow-up question in interviews is: "How would your algorithm change if the array could contain duplicates?"
Consider an array like [3, 1, 2, 3, 3, 3, 3].
If low=0 (nums[low]=3) and high=6 (nums[high]=3), then mid=3 (nums[mid]=3).
In this case, nums[low] == nums[mid] == nums[high]. We can't determine which side is sorted!
When this specific condition occurs, we can't make an intelligent decision to eliminate half the array. The safe fallback is to shrink the search space by one from both ends and try again.
// Inside the while loop, if this edge case occurs:
if (nums[low] == nums[mid] && nums[mid] == nums[high]) {
low++;
high--;
continue; // Continue to the next iteration
}
// ... rest of the logic
This handles the ambiguity. However, be aware that in the worst-case scenario (e.g., an array of all the same element except one), this fix degrades the time complexity to O(n) because you might have to shrink the array one element at a time. It's important to mention this trade-off in an interview.
Conclusion
Congratulations! You have now mastered another crucial variation of binary search. This problem is a testament to the idea that understanding the invariants (the rules that always hold true, like "one half is always sorted") is key to adapting algorithms to new challenges.
Key Takeaways:
- A rotated sorted array consists of two individually sorted segments.
- Standard binary search fails because the global monotonic property is broken.
- A modified binary search can achieve O(log n) time complexity by identifying the sorted half at each step and checking if the target lies within it.
- The presence of duplicates can create ambiguity, potentially degrading the worst-case performance to O(n) if not handled carefully.
Preview of the next lesson:
We'll be shifting gears from searching algorithms to a powerful array manipulation technique. In the next lesson, you will learn to apply prefix/suffix sum techniques to solve range query problems, which is an essential tool for efficiently calculating sums over various subarrays.