Searchin Rotated Sorted Array I I Algorithm

The Search in Rotated Sorted Array II Algorithm is an advanced binary search algorithm designed to find a target value in a rotated sorted array that may contain duplicates. A rotated sorted array is an array where the elements are sorted in ascending order, but have been rotated by an unknown number of steps. In this algorithm, the primary goal is to determine if a given target value exists within the rotated sorted array, even if there are duplicate values present. The algorithm takes advantage of the fact that a rotated sorted array can be divided into two subarrays, one of which is always sorted. The algorithm begins by initializing two pointers, low and high, at the beginning and end of the array, respectively. It then performs a binary search to find the target value. During the search, it first calculates the mid index between the low and high pointers. If the mid element matches the target, the algorithm terminates and returns true. Otherwise, it checks if the left half (from low to mid) is sorted. If it is sorted and the target lies within the sorted range, the algorithm adjusts the high pointer to mid - 1. If the target is not in the sorted range, the low pointer is adjusted to mid + 1. If the left half is not sorted, it implies that the right half (from mid to high) must be sorted. The algorithm then checks if the target lies within the sorted range of the right half and adjusts the pointers accordingly. This process is repeated until the target is found or the low pointer is greater than the high pointer. If the target is not found, the algorithm returns false.
class Solution {
public:
    bool search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int lf = 0, rt = n - 1;
        while (lf <= rt) {
            int m = lf + (rt - lf) / 2;
            if (A[m] == target)
                return true;
            
            if (A[lf] < A[m]) {
                if (A[lf] <= target && target < A[m])
                    rt = m - 1;
                else
                    lf = m + 1;
            }
            else if (A[lf] > A[m]) {
                if (A[m] < target && target <= A[rt])
                    lf = m + 1;
                else
                    rt = m - 1;
            }
            else {
                bool onleft = search(A + lf + 1, m - lf - 1, target);
                if (onleft) return true;
                return search(A + m + 1, rt - m, target);
            } 
                
        }
        return false;
    }
};

LANGUAGE:

DARK MODE: