ProgrammingHardAmazon OA · Infosys SP

What will be the output of the following pseudocode? (Arrays are indexed from 0)

What will be the output of the following pseudocode? (Arrays are indexed from 0)
Integer a[7] = {4, 2, 2, 8, 3, 3, 1}, cnt[0..8] = all 0, out[7]
for (each i from 0 to 6) cnt[a[i]] = cnt[a[i]] + 1
for (each v from 1 to 8) cnt[v] = cnt[v] + cnt[v - 1]
for (each i from 6 down to 0)
    cnt[a[i]] = cnt[a[i]] - 1
    out[cnt[a[i]]] = a[i]
end for
Print cnt[3], out[2], out[6]
  1. A. 3 2 8
  2. B. 5 3 8
  3. C. 4 2 8
  4. D. 3 2 4

Correct answer: A. 3 2 8

After the prefix sums, cnt[v] is the number of values ≤ v; placing elements from the right decrements cnt, so in the end cnt[3] points at the first 3 (index 3). out = {1, 2, 2, 3, 3, 4, 8}: out[2] = 2, out[6] = 8. Output 3 2 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic