LeetCode #81 Medium

Search in Rotated Sorted Array II

Search in Rotated Sorted Array II is LeetCode 81 (Medium). An array sorted in non-decreasing order, so values may repeat, was rotated at some unknown index. Return true if target is in it and false if not.

  • Repeats are the only change from the distinct-values version, and they cost speed: some arrays force a look at nearly every value, so the worst case is O(n).
  • The array holds 1 to 5000 values.
Constraints
  • 1 <= nums.length <= 5000
  • -10⁴ <= nums[i] <= 10⁴
  • nums is guaranteed to be rotated at some pivot.
  • -10⁴ <= target <= 10⁴
binary-searcharrays
Open on LeetCode ↗
02

Intuition

With distinct values, as in Search in Rotated Sorted Array, comparing the left end with the middle tells you which half is sorted. Repeats break that in one situation: when the left end equals the middle, the drop could be on either side. [1, 3, 1, 1, 1] and [1, 1, 1, 3, 1] both show a 1 at the left end and a 1 at the middle, yet the 3 is on different sides.

One small move is still safe then: drop the left end. It equals the middle, and the middle was just found not to be the target, so the left end is not the target either. The range shrinks by one instead of by half.

How to spot this pattern

A rotated sorted array that may hold repeats, with a yes/no lookup: the usual sorted-half test plus one fallback for a tie between the left end and the middle.

03

Approach

Try it first

Before reading on, write two rotated arrays with the same values at the left end and the middle but the drop on different sides. What can you still safely throw away when you see that tie? Then work out the worst-case running time.

1

Return on a match

Compute mid between lo and hi; if nums[mid] == target, return true straight away. The tie rule in the next step depends on knowing the middle value is not the target.

2

Left end equals the middle: shrink by one

If nums[lo] == nums[mid], neither half can be proved sorted. Set lo += 1. That value is a copy of the middle value, which is not the target, so nothing is lost.

3

Left end below the middle: the left half rises

If nums[lo] < nums[mid], there is no drop between them. Keep the left half (hi = mid - 1) when nums[lo] <= target < nums[mid], and move lo = mid + 1 otherwise.

4

Left end above the middle: the right half rises

Then the drop lies left of the middle, so mid to hi climbs. Move lo = mid + 1 when nums[mid] < target <= nums[hi], else hi = mid - 1. Once the range is empty, return false.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def search(self, nums: List[int], target: int) -> bool:
▶6 lo, hi = 0, len(nums) - 1
▶7 while lo <= hi:
▶8 mid = (lo + hi) // 2
▶9 if nums[mid] == target:
▶10 return True
▶11 if nums[lo] == nums[mid]:
▶12 lo += 1
▶13 elif nums[lo] < nums[mid]:
▶14 if nums[lo] <= target < nums[mid]:
▶15 hi = mid - 1
▶16 else:
▶17 lo = mid + 1
▶18 else:
▶19 if nums[mid] < target <= nums[hi]:
▶20 lo = mid + 1
▶21 else:
▶22 hi = mid - 1
▶23 return False
left endvsmiddletarget 010lo01121314hisearch indices 0 to 4 for 0
lo0
hi4
target0
Each pass compares the left end of the range with the middle. A smaller or bigger left end shows which half is sorted; an equal one shows nothing, and that is the case repeats add.
left end1=middle1target 010lo0112mid1314hileft end 1 = middle 1 → can't tell, drop the left end
mid2
nums[lo]1
lo1
Both ends of the left half hold 1, so the drop could be on either side. But the middle is not 0, and the left end is a copy of it, so dropping index 0 is safe. The range loses one value, not half.
left end0<middle1target 01001lo12mid1314hileft end 0 < middle 1 → left half rises
mid2
nums[lo]0
nums[mid]1
The left end is smaller than the middle, so no drop lies between them: indices 1 to 2 climb from 0 to 1.
left end0<middle1target 01001lohi12mid13140 fits 0 to 1 → keep index 1
lo1
hi1
The rising half covers every value from 0 to 1, and 0 is in that span, so only this half can hold it.
left end0vsmiddle0target 01001lomidhi121314middle holds 0 → true
mid1
answertrue
Index 1 holds the target, so return true. 3 passes came before this one.
05

Common pitfalls

Keeping the distinct-values test

✗ Wrong
if nums[lo] <= nums[mid]:
    # assume the left half is sorted
✓ Right
if nums[lo] == nums[mid]:
    lo += 1
elif nums[lo] < nums[mid]:

On a tie, <= trusts a left half that may hold the drop. On [1, 0, 1, 1, 1] with target 0, the left end and the middle are both 1, the code finds that 0 is not between 1 and 1, searches only the right side, and returns false.

06

Edge cases

One different value among copies, e.g. [1, 1, 1, 1, 1, 2, 1] with target 2

The first four middles all tie with the left end, so the range loses one value each time. Only then is the range indices 4 to 6, whose middle is the 2. This is the slow case the follow-up asks about.

07

Complexity

Time
O(n) worst case
Space
O(1)
Without ties each pass halves the range, about 13 passes for 5000 values. Each tie removes only one value, so an array that is nearly all one number can take close to n passes.
08

Search in Rotated Sorted Array II FAQ

Could a smarter algorithm stay O(log n) with duplicates?

No. Take an array of all 1s with a single 0 hidden somewhere. Every 1 you read looks the same whichever side the 0 is on, so any method may have to read almost every value before it finds the 0. The tie rule pays that price only when ties actually occur.

Some solutions move both ends on a tie. Is that needed?

Checking nums[lo] == nums[mid] == nums[hi] and moving both ends also works. Testing the left end alone is enough, though: if it differs from the middle, it is either smaller (left side rises) or bigger (the drop is on the left, so the right side rises).