Hello! In our previous lessons, we've sharpened our binary search skills, moving from the basic algorithm to sophisticated applications like finding the first and last occurrences of an element. This has trained us to think about how to adapt search algorithms when the data has specific properties, even if it's not perfectly straightforward.
Today, we'll take that skill a step further by tackling a classic interview problem: searching for an element in a rotated sorted array. Imagine a sorted array that has been "pivoted" or "rotated" at some unknown point. The global order is broken, but local sorted segments remain. Our task is to find a target element in logarithmic time, despite the rotation.
This lesson will teach you to solve this problem by modifying binary search. We will start with the version where all elements are unique, and then address the trickier case involving duplicates. Mastering this problem is excellent preparation for technical interviews, as it tests your ability to reason about array properties and adapt core algorithms.

1. The Brute-Force Approach: Linear Scan
As always, let's begin with the most direct solution. Since we need to find an element, we can simply iterate through the array from the beginning and check each element against our target. If we find it, we return its index. If we reach the end of the array without a match, we return -1.
Search Element in a Rotated Sorted Array - Tutorial
The "takeuforward" article starts by outlining this simple approach. It's a good baseline before we optimize.
Read the algorithm description and then look at the corresponding Java code. This should feel very familiar.
This linear search has a time complexity of . While correct, the problem's structure—a "rotated sorted" array—hints that we can do much better. The presence of sorted segments is a strong signal to apply a logarithmic-time approach like binary search.
2. Optimal Approach: Modified Binary Search for Unique Elements
A standard binary search won't work directly because the array isn't sorted end-to-end. If we pick a mid element, we can't reliably say whether the target is in the left or right half based on a simple comparison like target < nums[mid].
The key insight is that in any given range [low, high], at least one of the two halves—[low, mid] or [mid, high]—must be sorted. Our strategy will be to identify which half is sorted and then use that information to intelligently eliminate one half of the search space.
The following video provides an exceptional explanation of this core idea.
BS-4. Search Element in Rotated Sorted Array - I
This video from "take U forward" masterfully breaks down the logic. Pay close attention to how Striver explains the failure of standard binary search and introduces the "identify the sorted half" concept.
First, watch the segment from this timestamp to understand why binary search is the right direction to think in. Next, see why a naive binary search fails from this segment. Finally, watch the walkthrough from the core logic to see how identifying the sorted half allows us to correctly narrow the search space.
The Algorithm
Here is the step-by-step breakdown of the modified binary search:
- Initialize
low = 0andhigh = n - 1. - While
low <= high, calculatemid. - If
nums[mid] == target, we found it. Returnmid. - Identify the sorted half:
- Check if the left half is sorted:
if (nums[low] <= nums[mid]). - If it is, check if the
targetlies within the bounds of this sorted half (nums[low] <= target && target < nums[mid]).- If yes, the target must be in the left half, so eliminate the right:
high = mid - 1. - If no, the target must be in the unsorted right half:
low = mid + 1.
- If yes, the target must be in the left half, so eliminate the right:
- Else, the right half must be sorted (
nums[mid] <= nums[high]). - Check if the
targetlies within the bounds of this sorted right half (nums[mid] < target && target <= nums[high]).- If yes, the target must be here, so eliminate the left:
low = mid + 1. - If no, the target must be in the unsorted left half:
high = mid - 1.
- If yes, the target must be here, so eliminate the left:
- Check if the left half is sorted:
- If the loop finishes, the target was not found. Return
-1.

For a clean implementation and formal algorithm description, the takeuforward article is an excellent reference.
Search Element in a Rotated Sorted Array - Tutorial
This resource provides the complete algorithm and Java code for the optimal approach.
Start by reading the algorithm description, which formalizes the logic we just discussed. Carefully study the Java code to see how this logic translates into a working solution. Finally, review the complexity analysis, which confirms this is an O(\log n) solution.
3. The Plot Twist: Handling Duplicates
The previous solution works perfectly for arrays with unique elements. But what if the array contains duplicates? This introduces a subtle but critical edge case that can break our logic.
Consider an array like [3, 1, 3, 3, 3]. If low is at index 0, high is at index 4, then mid will be at index 2. Here, nums[low] = 3, nums[mid] = 3, and nums[high] = 3. In this scenario, nums[low] == nums[mid], which would normally imply the left half is sorted. However, that's not true ([3, 1, 3] is not sorted). Similarly, nums[mid] == nums[high] doesn't guarantee the right half is sorted.
When nums[low] == nums[mid] == nums[high], we are unable to determine which half is sorted.
BS-5. Search Element in Rotated Sorted Array II
Striver explains this exact problem in his follow-up video.
First, watch the recap and introduction to the problem with duplicates from this section. Pay close attention to the explanation of the failing edge case from this timestamp. He uses clear examples to show why our previous logic is no longer sufficient.
The Solution: Shrink and Conquer
How do we handle this ambiguous case? The solution is surprisingly simple. When we can't decide which half to eliminate, we can't make a logarithmic leap. Instead, we take a small, safe step: we shrink our search space by just one element from each end.
The Modified Algorithm (with Duplicates):
- Add a check at the beginning of your loop:
if (nums[low] == nums[mid] && nums[mid] == nums[high])- If this is true, we simply shrink the bounds:
low++,high--, andcontinueto the next iteration.
- If this is true, we simply shrink the bounds:
- The rest of the logic for identifying the sorted half and eliminating portions of the array remains exactly the same as in the unique elements case.
This small addition makes our algorithm robust enough to handle duplicates.
BS-5. Search Element in Rotated Sorted Array II
The same video provides the simple fix and discusses its performance implications.
Watch from this segment to see how shrinking the search space (low++, high--) resolves the ambiguity. Also, listen to the complexity discussion that follows.
Complexity with Duplicates
This change has a significant impact on the worst-case time complexity.
- Average Case: The algorithm still performs in time.
- Worst Case: In a scenario with many duplicates, such as
[3, 3, 3, 3, 1, 3, 3]where you're searching for1, the algorithm might have to shrink the search space linearly many times. This degrades the worst-case time complexity to . The space complexity remains .
The following article provides a superb, in-depth explanation, a full Java implementation, and a discussion of common pitfalls to avoid—essential for interview preparation.
81. Search in Rotated Sorted Array II - In-Depth Explanation
This AlgoMonster article is a comprehensive guide to the version with duplicates.
Read the Intuition section to understand the three cases: nums[mid] > nums[r], nums[mid] < nums[r], and the tricky nums[mid] == nums[r]. Follow the Solution Approach which details the step-by-step algorithm. Study the Java implementation carefully. Understand the complexity analysis, especially the reasoning for the O(n) worst case. Finally, read through the Common Pitfalls section. This is gold for avoiding off-by-one errors and other common mistakes during an interview.
Conclusion
Today, we've extended our binary search toolkit to handle a non-trivial variation: searching in a rotated sorted array. We saw how a key observation—that one half must always be sorted—allows us to adapt binary search for an efficient solution.
Key Takeaways:
- Core Strategy: In a rotated sorted array, always use binary search to identify the sorted half first (
[low, mid]or[mid, high]). Then, check if your target lies in that sorted half to decide which part of the array to eliminate. - Unique Elements: This strategy guarantees an solution.
- Duplicate Elements: An ambiguous case arises when
nums[low],nums[mid], andnums[high]are all equal. We handle this by safely shrinking the search space (low++,high--), which leads to an worst-case time complexity but preserves the average case.
In our next lesson, we will pivot from searching algorithms to a different application of the divide-and-conquer paradigm. We will explore how to adapt the logic of Merge Sort to solve the "Count Inversions" problem, a challenge that requires thinking about element pairs rather than just single targets.