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:])- A. 6 [9, 10]
- B. 7 [9, 10]
- C. 5 [9, 10]
- 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).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (Python list aliasing) python a = [1, 2, 3] b = a c = a[:] b.append(4) c.append(5) print(a, len(b), len(c))
- What is printed? (frequency of the most common character, ties to the earliest) python s = "programming" best = max(s, key=s.count)…
- Sliding window: what is printed? (maximum sum of any 3 consecutive elements) c int a[] = {4, -1, 6, -2, 3, 5, -4, 2}; int n = 8, k = 3, s…
- What is printed? (two-pointer: remove all occurrences of a value in place) cpp vector<int> a = {3, 2, 2, 3, 4, 3, 5}; int w = 0; for (int…
- What is printed? (stack: check if a sequence of pops is possible after pushing 1..n in order) python def valid(pushed, popped): st, j =…
- What is printed? (next greater element to the right, −1 if none) python a = [4, 5, 2, 25, 7, 8] res, st = [-1] len(a), [] for i in…