ExamAdda Logo

Search in a Rotated Sorted Array II

Medium

Given an integer array nums sorted in non-decreasing order and rotated at an unknown position, and an integer target, return true if target exists in nums, otherwise return false.

The array may contain duplicate values.

You must solve the problem using O(log n) time on average.

Example 1

Input

nums = [2,5,6,0,0,1,2]
target = 0

Output

true

Explanation

The target 0 exists in the array.

Example 2

Input

nums = [2,5,6,0,0,1,2]
target = 3

Output

false

Explanation

The target 3 does not exist in the array.

Constraints

1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
nums is sorted in non-decreasing order before rotation.
nums may contain duplicates.
-10^4 <= target <= 10^4

Hints:

Hint 1

Use binary search, but first determine which half of the array is normally sorted.

Hint 2

If nums[left] == nums[mid] == nums[right], duplicates make it impossible to determine which half is sorted. In that case, move left forward and right backward.

Auto
Loading editor...
Input

Expected Output