Statement▼
You are required to find an integer value target in an array arr of non-distinct integers. Before being passed as input to your search function, arr has been processed as follows:
It has been sorted in non-descending order.
It has been rotated around some pivot
k , such that, after rotation, it looks like this:[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]. For example,[10, 30, 40, 42, 42, 47, 78, 90, 901], rotated around pivotk=5 becomes[47, 78, 90, 901, 10, 30, 40, 42, 42].
Return TRUE if t exists in the rotated, sorted array arr, and FALSE otherwise, while minimizing the number of operations in the search.
Note: In this problem, the value of
k is not passed to your search function.
Constraints
1≤ arr.length≤1000 −104≤ arr[i]≤104 arris guaranteed to be rotated at some pivot index.−104≤ t≤104
Solution
The challenge is efficiently searching for a target value within a rotated array. Even when the array is rotated, at least one part will still be sorted. To find the target, the algorithm uses a modified binary search. During the search, the algorithm first identifies which segment of the array (either the left or right half) is sorted. Based on the sorted segment, the algorithm determines if the target value lies within that segment. If it does, the search is narrowed to that half of the array. If not, the search continues in the other half. When the array contains duplicates, it can make it harder to identify the sorted segment. In such cases, the algorithm adjusts the search space by skipping over the duplicates.
The steps of the algorithm are as follows:
Initialize two pointers,
leftat the beginning of the array andrightat the end.Calculate the middle index
mid.Check if
arr[mid]is equal totarget. If yes, returnTRUE.If
arr[left]toarr[mid]is sorted:Check if the
targetlies within this range. If so, move therightpointer tomid - 1.Otherwise, move the
leftpointer tomid + 1.
If
arr[mid]toarr[right]is sorted:Check if
targetlies within this range. If yes, move theleftpointer tomid + 1.Otherwise, move the
rightpointer tomid - 1.
If the array contains duplicates, the algorithm can’t determine which part is sorted due to the elements at
left,mid, andrightbeing equal. Specifically, this happens whenarr[left] == arr[mid] && arr[mid] == arr[right].In such cases, it’s difficult to determine whether the sorted segment is on the left or right side. To overcome this, the algorithm increments theleftpointer by one (left += 1) to skip over the duplicate, thereby reducing the search space. This step helps the algorithm progress even when it encounters a block of identical elements that could otherwise prevent it from identifying the sorted segment. Alternatively, the algorithm can handle duplicates by decrementing therightpointer (right -= 1).Repeat steps
2−6 untilleftexceedsright.If the loop exits without finding the target, return
FALSE.
Let’s look at the following illustration to get a better understanding of the solution: