ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (counting distinct substrings of length 2)?

What will be the output of the following pseudocode (counting distinct substrings of length 2)?
String s = "abab"
Set subs = empty set
for (each i from 0 to length(s) - 2)
    add(subs, substring(s, i, i + 2))
end for
Print size(subs)
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 1

Correct answer: B. 2

The length-2 substrings scanned are 'ab' (i=0), 'ba' (i=1), 'ab' (i=2); the set keeps only distinct ones, {'ab', 'ba'}, giving size 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic