Search In Rotated Sorted Array Ii
To solve this coding challenge, we can use a modified binary search algorithm to adapt it to the properties of a rotated sorted array, even if the array contains duplicates. The key steps involve adjusting the binary search conditions to handle the potential duplicate values and ensuring that we search in the correct half of the rotated array.
Firstly, let's break down the problem. Given a rotated sorted array
, we need to determine whether a target value exists within this array. The array was rotated at an unknown pivot point, and it contains elements that are non-distinct.
nums
Explanation:
-
Initialization
: Start with two pointers (
and
left), which point to the beginning and the end of the array, respectively.right -
Binary Search Loop
: Use a while loop to perform binary search until
exceeds
left.right -
Middle Calculation
: Calculate the middle index
. This index will help us determine if we need to search in the left or right half of the array.
mid -
Target Check
: If
equals the target, return
nums[mid]immediately.True -
Handle Duplicates
: If
equals
nums[left], increment thenums[mid]pointer to skip duplicates. This step is crucial to handle the situation where duplicates might be at the edges of our current search window, potentially misleading the determination of which half is sorted.left -
Left Sorted Half
: If
is less than or equal to
nums[left], it means the left half of the array is sorted:nums[mid] -
Check if the target lies within the range of
and
nums[left].nums[mid] -
If it does, adjust the
pointer to search in the left half.
right -
Otherwise, adjust the
pointer to search in the right half.
left -
Right Sorted Half
: If
is less than
nums[mid], it means the right half is sorted:nums[right] -
Check if the target lies within the range of
and
nums[mid].nums[right] -
If it does, adjust the
pointer to search in the right half.
left -
Otherwise, adjust the
pointer to search in the left half.
right -
Terminate and Return
: If the target is found, return
. If the loop exits without finding the target, return
True.False - Initialize variables :
- Binary Search Loop :
- Terminate and Return :
Detailed Steps in Pseudocode:
left = 0 # Starting index of the array
right = len(nums) - 1 # Last index of the array
WHILE left <= right:
mid = (left + right) // 2 # Calculate the middle index
IF nums[mid] == target:
RETURN True # Target found at the mid index
# Handle duplicates
WHILE left < mid AND nums[left] == nums[mid]:
left += 1 # Move left pointer to skip duplicates
# Check if the left half is sorted
IF nums[left] <= nums[mid]:
IF nums[left] <= target < nums[mid]:
right = mid - 1 # Target is in the left half
ELSE:
left = mid + 1 # Target is in the right half
# Check if the right half is sorted
ELSE:
IF nums[mid] < target <= nums[right]:
left = mid + 1 # Target is in the right half
ELSE:
right = mid - 1 # Target is in the left half
RETURN False # Target not found in the array