ProgrammingHardTCS NQT · Accenture

The number of non-empty substrings of "abcd" (substrings are contiguous pieces, counted by position) is computed by the procedure below. What is printed?

The number of non-empty substrings of "abcd" (substrings are contiguous pieces, counted by position) is computed by the procedure below. What is printed?
count = 0
for i = 0 to n - 1
    for j = i to n - 1: count = count + 1
end for
Print count
  1. A. 6
  2. B. 16
  3. C. 8
  4. D. 10

Correct answer: D. 10

Substrings of length 1, 2, 3 and 4 number 4, 3, 2 and 1, giving 10 in total. Requiring j greater than i gives 6, the number of subsets is 16, and adding the distinct count to the length gives 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic