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?
  1. A. (1, 2, 4) (-1, -1, 4)
  2. B. (2, 1, 4) (-1, -1, 3)
  3. C. (2, 1, 4) (-1, -1, 4)
  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

Exams that ask this topic