ProgrammingVery hardTCS NQT · Accenture

Pattern "aba" is searched in the text "abababa" with overlapping matches allowed. The procedure below counts the starting positions where the pattern occurs. What is printed?

Pattern "aba" is searched in the text "abababa" with overlapping matches allowed. The procedure below counts the starting positions where the pattern occurs. What is printed?
count = 0
for i = 0 to len(text) - len(pattern)
    if text[i .. i+len(pattern)-1] == pattern then count = count + 1
end for
Print count
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 7

Correct answer: B. 3

The matches start at positions 0, 2 and 4, which gives 3 overlapping occurrences. Skipping past each match gives only 2, counting the letter a gives 4, and printing the text length gives 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic