Data Structures & AlgorithmsEasyInfosys SP/DSE · Product Company SDE
Problem: Find the minimum of a rotated sorted array of distinct values.
Problem: Find the minimum of a rotated sorted array of distinct values.
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
else:
hi = mid
return a[lo]
print(find_min([4, 5, 6, 7, 0, 1, 2]), find_min([11, 13, 15, 17]), find_min([2, 1]))What is printed?- A. 0 11 1
- B. 0 17 1
- C. 0 11 2
- D. 1 11 1
Correct answer: A. 0 11 1
Compare with the right end: if a[mid] > a[hi] the drop is to the right of mid, else the minimum is at mid or to its left. A non-rotated array keeps moving hi left to index 0. O(log n). Comparing with a[lo] instead fails on the non-rotated case.
More Coding Interview Problems questions
- Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining…
- Problem: A courier eats through n ≤ 10⁵ piles of parcels, pile sizes up to 10⁹, at speed k per hour (a pile smaller than k still takes a…
- Problem: Place c routers at given positions on a road so the minimum distance between any two routers is as large as possible. python def…
- Problem: The function below should return the integer square root ⌊√x⌋. java static int isqrt(int x) { int lo = 0, hi = x, ans = 0; while…
- Problem: In an array where every element appears twice except one, and pairs sit next to each other, the array is sorted. Find the single…
- Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index. python def peak(a)…