Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot.
Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot.
def search(a, t):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == t: return mid
if a[lo] <= a[mid]:
if a[lo] <= t < a[mid]: hi = mid - 1
else: lo = mid + 1
else:
if a[mid] < t <= a[hi]: lo = mid + 1
else: hi = mid - 1
return -1
a = [15, 18, 22, 3, 6, 9, 12]
print(search(a, 6), search(a, 18), search(a, 10))What is printed?- A. 4 1 5
- B. 3 1 -1
- C. 4 1 -1
- D. -1 1 -1
Correct answer: C. 4 1 -1
One half around mid is always sorted; check whether the target lies in that sorted half, else go to the other half. 6 is at index 4, 18 at index 1, 10 is absent. O(log n). Using a[lo] < a[mid] (strict) breaks when lo == mid.
More Coding Interview Problems questions
- Problem: Find the minimum of a rotated sorted array of distinct values. python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid =…
- 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…