ProgrammingModerateAmazon OA · TCS NQT

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[6] = {1, 2, 1, 3, 2, 1}
Map cnt = empty
Integer pairs = 0
for (each i from 0 to 5)
    pairs = pairs + cnt[a[i]]          // cnt of an unseen value is 0
    cnt[a[i]] = cnt[a[i]] + 1
end for
Print pairs
  1. A. 6
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: C. 4

Each element pairs with every earlier equal element. The three 1's give C(3, 2) = 3 pairs and the two 2's give 1: pairs = 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic