Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

Merge two sorted halves and count comparisons. What is printed?

Merge two sorted halves and count comparisons. What is printed?
L, R = [1, 4, 6, 9], [2, 3, 10]
i = j = comps = 0; out = []
while i < len(L) and j < len(R):
    comps += 1
    if L[i] <= R[j]: out.append(L[i]); i += 1
    else: out.append(R[j]); j += 1
out += L[i:] + R[j:]
print(comps, out[-2:])
  1. A. 6 [9, 10]
  2. B. 7 [9, 10]
  3. C. 5 [9, 10]
  4. D. 6 [6, 9]

Correct answer: A. 6 [9, 10]

Comparisons: 1–2, 4–2, 4–3, 4–10, 6–10, 9–10; then L is exhausted and 10 is copied without comparing. That is 6 = m + n − 1, the worst case, because the lists interleave until the very end. The tail gives [9, 10]. Merging is O(m + n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic