Problem Description
Given a rotated sorted array (which may contain duplicate elements) and an integer target, determine if the target exists in the array. The array is originally sorted in non-decreasing order and then rotated at an unknown pivot. The challenge is to reduce the overall operational steps as much as possible.
Key Insights
- The array is rotated, so one of the two halves will always be sorted.
- Duplicates can complicate the binary search by obscuring which half is sorted.
- When duplicates cause ambiguity (i.e., when nums[low], nums[mid], and nums[high] are equal), the search space is reduced by incrementally moving the boundaries.
- A modified binary search can efficiently search the array on average, though the worst-case runtime can degrade to O(n) due to duplicates.
Space and Time Complexity
Time Complexity: Worst-case O(n), Average-case O(log n)
Space Complexity: O(1)
Solution
The solution employs a modified binary search technique. The main algorithm works by maintaining two pointers (low and high) and calculating a mid-point. If the target is equal to the element at the mid, the algorithm returns true. If duplicates are detected at the low, mid, and high indices, the boundaries are adjusted to avoid ambiguity. Otherwise, the algorithm determines if the left or right side is sorted; if the target lies within the sorted portion, it moves the boundaries accordingly. This method accounts for potential duplicate values influencing the decision process.