Data Structures & AlgorithmsHardProduct company OA

Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES.

Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES.
def find_min(a):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] > a[hi]: lo = mid + 1
        elif a[mid] < a[hi]: hi = mid
        else: hi -= 1
    return a[lo]
print(find_min([4, 4, 5, 1, 2, 4]), find_min([2, 2, 2, 0, 2]), find_min([3, 1, 3, 3, 3]))
What is printed?
  1. A. 1 0 3
  2. B. 4 0 1
  3. C. 1 2 1
  4. D. 1 0 1

Correct answer: D. 1 0 1

Compare a[mid] with a[hi]: larger → the minimum is right of mid; smaller → at mid or left. When they are equal you cannot tell which side holds the drop ([2, 2, 2, 0, 2] vs [2, 0, 2, 2, 2]), so only hi can be safely discarded (hi −= 1). This makes the worst case O(n), e.g. all values equal; with distinct values it is O(log n).

More Coding Interview Problems questions

Exams that ask this topic