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])
- A. [1, 2, 1, 1, 3] 3
- B. [1, 3, 4, 5, 8] 2
- C. [1, 3, 4, 5, 8] 3
- 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.
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
- How many swaps does this bubble sort make, and how many passes run? python a = [5, 1, 4, 2, 8] swaps = passes = 0 for i in range(len(a)…
- Insertion sort counts element shifts. What is printed? python a = [3, 7, 1, 5, 2] shifts = 0 for i in range(1, len(a)): key, j = a[i], i…
- Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index? python…
- Merge two sorted halves and count comparisons. What is printed? python L, R = [1, 4, 6, 9], [2, 3, 10] i = j = comps = 0; out = [] while i…
- 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)…