ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (substring(s, i, len) is len characters starting at index i; a Set keeps one copy of each value)

What will be the output of the following pseudocode? (substring(s, i, len) is len characters starting at index i; a Set keeps one copy of each value)
String s = "ABAB"
Set seen = empty
for (each i from 0 to length(s) - 1)
    for (each len from 1 to length(s) - i)
        add substring(s, i, len) to seen
    end for
end for
Print size(seen)
  1. A. 10
  2. B. 8
  3. C. 7
  4. D. 6

Correct answer: C. 7

There are 10 substrings by position, but repeats are stored once: A, B, AB, BA, ABA, BAB, ABAB — 7 distinct ones.

More Pseudocode and Code Tracing questions

Exams that ask this topic