Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (counting sort on small values)

What is printed? (counting sort on small values)
a = [4, 1, 3, 4, 2, 1, 0, 4]
cnt = [0] * 5
for x in a: cnt[x] += 1
for i in range(1, 5): cnt[i] += cnt[i - 1]
print(cnt, cnt[4] - cnt[3])
  1. A. [1, 2, 1, 1, 3] 3
  2. B. [1, 3, 4, 5, 8] 2
  3. C. [1, 3, 4, 5, 8] 3
  4. D. [0, 1, 3, 4, 5] 3

Correct answer: C. [1, 3, 4, 5, 8] 3

Raw counts are 1, 2, 1, 1, 3; the prefix sums give the end position of each value's block in the output: [1, 3, 4, 5, 8]. cnt[4] − cnt[3] recovers the number of 4s (3). Counting sort is O(n + k) and stable when filled from the right.

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

Exams that ask this topic