Skip to main content

Search in Rotated Sorted Array II


Search in Rotated Sorted Array II: 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

Constraints:
  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • nums is guaranteed to be rotated at some pivot.
  • -10^4 <= target <= 10^4

Try this Problem on your own or check similar problems:

  1. Search in Rotated Sorted Array
Solution:
public boolean search(int[] nums, int target) {
int start = 0, end = nums.length-1;
while(start <= end){
int mid = start + (end - start) / 2;

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

if((nums[start] == nums[mid]) && (nums[end] == nums[mid]))
{
++start;
--end;
}else if(nums[mid] > target){
if(nums[mid] >= nums[start] && nums[start] > target){
start = mid + 1;
}else{
end = mid - 1;
}
}else{
if(nums[mid] <= nums[end] && nums[end] < target){
end = mid - 1;
}else{
start = mid + 1;
}
}
}
return false;
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Explanation:

The only difference from Search in Rotated Sorted Array is that now we have duplicates in the input array. If we encounter duplicates we just skip them by moving the start to the right, and end to the left (e.g. 1, 1, 1, 0, 1 with target 0 we can just skip initial start and end since they are equal to the mid, and none of them is equal to the target), otherwise the algorithm works as the one without duplicates. In the worst case we will have time complexity of O(n) (linear search, e.g. nums = [1,1,1,1,1], target = 2 we will just iterate over the whole array in linear fashion).