Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second).

Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second).
def merge(a, m, b, n):
    i, j, k = m - 1, n - 1, m + n - 1
    while j >= 0:
        if i >= 0 and a[i] > b[j]:
            a[k] = a[i]; i -= 1
        else:
            a[k] = b[j]; j -= 1
        k -= 1
    return a
print(merge([2, 5, 9, 0, 0, 0], 3, [1, 5, 6], 3))
What is printed?
  1. A. [1, 2, 5, 6, 9, 0]
  2. B. [2, 5, 9, 1, 5, 6]
  3. C. [1, 2, 5, 5, 6, 9]
  4. D. [1, 2, 5, 6, 5, 9]

Correct answer: C. [1, 2, 5, 5, 6, 9]

Filling from the back avoids overwriting unread values in a. The loop stops when b is exhausted; leftover a values are already in place. O(m + n), O(1) extra space. Merging from the front would overwrite a[i] before it is read.

More Coding Interview Problems questions

Exams that ask this topic