Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: A 3 × 4 matrix is sorted row-wise and each row starts after the previous row ends. Search it as one virtual sorted array of R·C cells (also count the probes).
Problem: A 3 × 4 matrix is sorted row-wise and each row starts after the previous row ends. Search it as one virtual sorted array of R·C cells (also count the probes).
def search(m, t):
R, C = len(m), len(m[0]); lo, hi = 0, R * C - 1; steps = 0
while lo <= hi:
mid = (lo + hi) // 2; steps += 1
v = m[mid // C][mid % C]
if v == t: return (mid // C, mid % C, steps)
if v < t: lo = mid + 1
else: hi = mid - 1
return (-1, -1, steps)
m = [[2, 4, 7, 9], [11, 15, 18, 21], [25, 30, 33, 40]]
print(search(m, 30), search(m, 10))What is printed?- A. (1, 2, 4) (-1, -1, 4)
- B. (2, 1, 4) (-1, -1, 3)
- C. (2, 1, 4) (-1, -1, 4)
- D. (2, 1, 3) (-1, -1, 4)
Correct answer: C. (2, 1, 4) (-1, -1, 4)
Index k maps to cell (k // C, k % C). For 30: mids 5 (15), 8 (25), 10 (33), 9 (30) → found at row 2, column 1 after 4 probes. For 10: mids 5 (15), 2 (7), 3 (9), 4 (11) → lo > hi, absent after 4 probes. O(log(R·C)).
More Coding Interview Problems questions
- Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded. python def…
- Problem: Reorder the letters of s so that letters listed in order appear in that order; letters not in order go last, keeping their…
- Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i]…
- Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES. python def findmin(a): lo, hi = 0, len(a) - 1 while lo <…
- 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…