oneby7

Binary Search Searching a sorted array

236. Search in Rotated Sorted Array II

Medium

You are given an array of integers nums and an integer target. The array was sorted in non-decreasing order and then rotated. Values can repeat. Return true if target is in nums, and false if it is not.

Rotating an array by k takes its first k elements off the front and puts them, in the same order, at the back. For example, [1,3,3,5,8] rotated by 3 is [5,8,1,3,3]. The rotation can be any amount from 0 to nums.length − 1, and you are not told which.

This is Search in Rotated Sorted Array with repeated values allowed. Keep the search fast, and think about how the repeats change its worst case.

Example 1

Input: nums = [3, 3, 1, 2, 3, 3, 3, 3, 3], target = 1

Output: true

Explanation: The array is [1,2,3,3,3,3,3,3,3] rotated by 7. In nums itself, 1 sits at index 2.

Example 2

Input: nums = [9, 12, 12, -4, 0, 0, 5], target = 3

Output: false

Explanation: 3 would fall between 0 and 5, but no element of nums equals it.

Example 3

Input: nums = [5, 5, 5, 5, 5], target = 5

Output: true

Explanation: Every element is 5, so every rotation of this array looks the same.

Check your understanding

Work out the answer for this input before you write any code.

nums = [4, 2, 4, 4, 4], target = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • -109 ≤ target ≤ 109
  • nums is a non-decreasing array rotated by some amount from 0 to nums.length − 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.