Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Search a rotated array with repeated values

Medium · Target 20 minutes · Binary search · Type asked atMetaMicrosoft

An array of integers, sorted in non-decreasing order and possibly containing repeated values, has been rotated at an unknown point. Given the rotated array nums and a target, return true if target occurs in it and false otherwise.

Examples

InputOutputWhy
nums = [2, 5, 6, 0, 0, 1, 2], target = 0true
nums = [2, 5, 6, 0, 0, 1, 2], target = 3false
nums = [1, 0, 1, 1, 1], target = 0trueThe ends and the middle are all 1: the 0 could be on either side.

Constraints

  • 1 ≤ n ≤ 5000
  • −10⁴ ≤ nums[i], target ≤ 10⁴

Hints

Hint 1

Start from the distinct-values version: compare nums[lo] with nums[mid] to find the sorted half.

Hint 2

Try [1, 0, 1, 1, 1] and [1, 1, 1, 0, 1]. Both have nums[lo] = nums[mid] = nums[hi] = 1, but the 0 is on different sides.

Hint 3

In that case, nums[lo] and nums[hi] are not the target (nums[mid] already was not), so both can be dropped: lo += 1, hi −= 1.

Where people lose marks

  • Treating nums[lo] ≤ nums[mid] as proof that the left half is sorted when nums[hi] is the same value as well.
  • Claiming O(log n) for every input: an interviewer will ask for the worst case.
  • Shrinking only one end in the ambiguous case: correct, but it needs a separate argument that the dropped end is not the target.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.