Search in Rotated Sorted Array II LeetCode Solution

Last updated on January 29th, 2025 at 02:21 am

Here, we see a Search in Rotated Sorted Array II LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Array, Binary Search

Level of Question

Medium

Search in Rotated Sorted Array II LeetCode Solution

Search in Rotated Sorted Array II LeetCode Solution

1. Problem Statement

There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].

Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

You must decrease the overall operation steps as much as possible.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is Modified Binary Search. This pattern is a variation of the standard binary search algorithm, where the search space is adjusted based on additional conditions. In this case, the array is rotated and may contain duplicates, so the algorithm modifies the binary search logic to handle these scenarios.

3. Code Implementation in Different Languages

3.1 Search in Rotated Sorted Array II C++

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int l = 0, r = nums.size() - 1;
        while (l <= r) {
            while (l < r && nums[l] == nums[l + 1]) {
                l++;
            }
            while (l < r && nums[r] == nums[r - 1]) {
                r--;
            }
            int m = l + (r - l) / 2;
            if (nums[m] == target) {
                return true;
            }
            if (nums[m] > target) {
                if (nums[l] > nums[m] || nums[l] <= target) {
                    r = m - 1;
                } else {
                    l = m + 1;
                }
            } else {
                if (nums[l] <= nums[m] || nums[l] > target) {
                    l = m + 1;
                } else {
                    r = m - 1;
                }
            }
        }
        return false;   
    }
};

3.2 Search in Rotated Sorted Array II Java

class Solution {
    public boolean search(int[] nums, int target) {
        int start = 0, end = nums.length - 1, mid = -1;
        while(start <= end) {
            mid = (start + end) / 2;
            if (nums[mid] == target) {
                return true;
            }
            if (nums[mid] < nums[end] || nums[mid] < nums[start]) {
                if (target > nums[mid] && target <= nums[end]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            } else if (nums[mid] > nums[start] || nums[mid] > nums[end]) {
                if (target < nums[mid] && target >= nums[start]) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } else {
                end--;
            }
        }
        return false;        
    }
}

3.3 Search in Rotated Sorted Array II JavaScript

var search = function(nums, target) {
    function findPivot(low, high) {
        if(high - low === 1 && nums[high] < nums[low]) return high;
        if(high - low <= 1) return 0;
        const mid = Math.floor((low + high) / 2);
        if(nums[mid] > nums[high]) return findPivot(mid, high);
        if(nums[mid] < nums[low]) return findPivot(low, mid);
        return Math.max(findPivot(low, mid), findPivot(mid, high));
    }
    function binarySearch(start, end) {
        while(start <= end) {
            const mid = Math.floor((start + end) / 2);    
            if(nums[mid] === target) return true;
            if(nums[mid] > target) end = mid - 1;
            else start = mid + 1;
        }
        return false;
    }
    const minIdx = findPivot(0, nums.length-1)
    return binarySearch(0, minIdx-1) || binarySearch(minIdx, nums.length-1)  
};

3.4 Search in Rotated Sorted Array II Python

class Solution(object):
    def search(self, nums, target):
        left,right = 0,len(nums)-1
        while left <=  right:
	        mid = (left+right) // 2
	        if nums[mid] == target:
		        return True
	        if nums[left] <= nums[mid]:
		        if nums[left] == nums[mid] and mid != left:
			        left+=1
			        continue
		        if nums[left] <= target< nums[mid]:
			        right = mid-1
		        else: left = mid+1
	        elif nums[left] > nums[mid]:
		        if nums[mid] < target <= nums[right]:
			        left = mid+1
		        else: right = mid-1
        return False

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(log n)O(1)
JavaO(log n)O(1)
JavaScriptO(log n)O(log n)
PythonO(log n)O(1)
  • The provided code in all languages implements a Modified Binary Search to handle rotated sorted arrays with potential duplicates.
  • The algorithm efficiently narrows down the search space by determining which part of the array is sorted and whether the target lies in that part.
  • The time complexity is O(log n), and the space complexity varies slightly depending on the language implementation.
Scroll to Top