KatInterview

81. Search in Rotated Sorted Array II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to search for a target value in a rotated sorted array that may contain duplicates. This is a follow-up to the "Search in Rotated Sorted Array" problem, with the key difference being the allowance of duplicate values. The presence of duplicates introduces a challenging scenario where standard binary search logic for rotated arrays fails. Specifically, when nums[left] == nums[mid], we cannot definitively determine which half of the array is sorted. For instance, in an array like [3, 1, 2, 3, 3, 3, 3], if left=0, mid=3, nums[left] is 3 and nums[mid] is 3, but the left half is not sorted. This ambiguity requires a modification to the standard binary search algorithm.

Solution

Search in Rotated Sorted Array II in Python

class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        left, right = 0, len(nums) - 1

        while left <= right:
            mid = left + (right - left) // 2

            if nums[mid] == target:
                return True

            # The ambiguous case: nums[left] == nums[mid]
            # We can't determine which part is sorted.
            # For example, [1, 0, 1, 1, 1] or [1, 1, 1, 0, 1].
            # In this case, we can safely discard nums[left] since it's a
            # duplicate of nums[mid] and we know nums[mid] is not the target.
            if nums[left] == nums[mid]:
                left += 1
                continue

            # Left half is sorted
            if nums[left] < nums[mid]:
                # Target is in the sorted left half
                if nums[left] <= target < nums[mid]:
                    right = mid - 1
                else:
                    left = mid + 1
            # Right half is sorted
            else: # nums[left] > nums[mid]
                # Target is in the sorted right half
                if nums[mid] < target <= nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1
        
        return False

Search in Rotated Sorted Array II in Java

class Solution {
    public boolean search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                return true;
            }

            // The case where we can't determine which side is sorted.
            // Example: [1, 0, 1, 1, 1] or [1, 1, 1, 0, 1]
            // In this case, nums[left] is a duplicate of nums[mid]. Since we
            // already checked nums[mid] != target, we can safely discard nums[left].
            if (nums[left] == nums[mid]) {
                left++;
                continue;
            }

            // Check if the left half [left...mid] is sorted
            if (nums[left] < nums[mid]) {
                // Check if target is in the sorted left half
                if (target >= nums[left] && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } 
            // Otherwise, the right half [mid...right] is sorted
            else { // nums[left] > nums[mid]
                // Check if target is in the sorted right half
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }

        return false;
    }
}

Search in Rotated Sorted Array II in C++

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int left = 0;
        int right = nums.size() - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                return true;
            }

            // The case where we can't determine which side is sorted.
            // For example, [1, 0, 1, 1, 1] or [1, 1, 1, 0, 1].
            // In this case, nums[left] is a duplicate of nums[mid]. Since we
            // already checked nums[mid] != target, we can safely discard nums[left].
            if (nums[left] == nums[mid]) {
                left++;
                continue;
            }

            // Check if the left half [left...mid] is sorted
            if (nums[left] < nums[mid]) {
                // Check if target is in the sorted left half
                if (target >= nums[left] && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    // Target is in the unsorted right half
                    left = mid + 1;
                }
            } 
            // Otherwise, the right half [mid...right] is sorted
            else { // nums[left] > nums[mid]
                // Check if target is in the sorted right half
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    // Target is in the unsorted left half
                    right = mid - 1;
                }
            }
        }

        return false;
    }
};

Search in Rotated Sorted Array II in TypeScript

function search(nums: number[], target: number): boolean {
    let left = 0;
    let right = nums.length - 1;

    while (left <= right) {
        let mid = Math.floor(left + (right - left) / 2);

        if (nums[mid] === target) {
            return true;
        }

        // The ambiguous case where we cannot determine which half is sorted.
        // For example, [1, 0, 1, 1, 1] or [1, 1, 1, 0, 1].
        // In this scenario, nums[left] is a duplicate of nums[mid].
        // Since we've already confirmed nums[mid] is not the target,
        // we can safely discard nums[left] and continue.
        if (nums[left] === nums[mid]) {
            left++;
            continue;
        }

        // Check if the left half [left...mid] is sorted
        if (nums[left] < nums[mid]) {
            // Check if target is within the sorted left half
            if (target >= nums[left] && target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } 
        // Otherwise, the right half [mid...right] is sorted
        else { // nums[left] > nums[mid]
            // Check if target is within the sorted right half
            if (target > nums[mid] && target <= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }

    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.