ProgrammingHardAmazon OA · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
String s = "ABCAB"
Integer cnt[26] = all 0, total = 0
for (each ch in s)
    cnt[ch] = cnt[ch] + 1
    total = total + cnt[ch]
end for
Print total
  1. A. 5
  2. B. 7
  3. C. 9
  4. D. 15

Correct answer: B. 7

When a letter is seen for the k-th time it can end k substrings that start with the same letter (including itself). So total counts substrings whose first and last letters match: A: 1 + 2, B: 1 + 2, C: 1, total 7 (A, B, C, A, B, ABCA, BCAB).

More Pseudocode and Code Tracing questions

Exams that ask this topic