Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Find a target's index in a rotated sorted array of distinct values in O(log n).
Problem: Find a target's index in a rotated sorted array of distinct values in O(log n).
def search(a, t):
lo, hi = 0, len(a) - 1
while lo <= hi:
m = (lo + hi) // 2
if a[m] == t: return m
if a[lo] <= a[m]:
if a[lo] <= t < a[m]: hi = m - 1
else: lo = m + 1
else:
if a[m] < t <= a[hi]: lo = m + 1
else: hi = m - 1
return -1
print(search([15, 18, 22, 3, 7, 9, 11], 9), search([15, 18, 22, 3, 7, 9, 11], 16))What is printed?- A. 5 0
- B. 4 -1
- C. 6 -1
- D. 5 -1
Correct answer: D. 5 -1
At least one half around mid is sorted; check whether the target lies in that half's range. 9 is found at index 5. 16 would lie between 15 and 18 but is absent, so the search ends with −1.
More Coding Interview Problems questions
- Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an…
- Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to…
- Problem: Length of the longest common subsequence of THREE strings (3-D DP). python def lcs3(a, b, c): dp = [[[0] (len(c) + 1) for in…
- Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS. python from functools…
- Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two…
- Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i'…