ProgrammingHardTCS NQT · Accenture

The procedure below scans the string "abracadabra" from left to right and counts how many letters are repeats of an earlier letter (a letter already seen, counted each time it appears again). What is printed?

The procedure below scans the string "abracadabra" from left to right and counts how many letters are repeats of an earlier letter (a letter already seen, counted each time it appears again). What is printed?
seen = empty set; repeats = 0
for each letter ch
    if ch in seen then repeats = repeats + 1 else add ch to seen
end for
Print repeats
  1. A. 6
  2. B. 5
  3. C. 7
  4. D. 0

Correct answer: A. 6

abracadabra has 11 letters and 5 distinct ones, so 6 letters are repeats. Printing the distinct count gives 5, adding one to the difference of length and distinct count gives 7, and never adding to seen gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic