ProgrammingVery hardTCS NQT · Accenture

The string "aabbc" is examined by the procedure below, which counts the substrings (contiguous pieces, counted by position) that contain exactly 2 distinct characters. What is printed?

The string "aabbc" is examined by the procedure below, which counts the substrings (contiguous pieces, counted by position) that contain exactly 2 distinct characters. What is printed?
count = 0
for i = 0 to n - 1
    for j = i to n - 1
        if the substring s[i..j] has exactly 2 distinct characters then count = count + 1
    end for
end for
Print count
  1. A. 8
  2. B. 6
  3. C. 7
  4. D. 2

Correct answer: B. 6

The substrings with exactly two distinct letters are aab, aabb, ab, abb, bbc and bc, which is 6. Counting substrings with at least two distinct letters gives 8, counting the single-letter substrings gives 7, and counting substrings with three distinct letters gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic