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?- A. 1 0 3
- B. 4 0 1
- C. 1 2 1
- 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
- Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the…
- Problem: A company sends 2n candidates to two interview centres, n to each; costs[i] = (cost at A, cost at B). Minimise the total cost by…
- Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency. python from collections import…
- Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest…
- Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card…
- Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left…