ProgrammingHardTCS NQT · Accenture

The string "bananana" is searched for "ana" with overlapping occurrences allowed. The procedure below counts the start positions of matches. What is printed?

The string "bananana" is searched for "ana" with overlapping occurrences allowed. The procedure below counts the start positions of matches. What is printed?
count = 0
for i = 0 to len(s) - 3
    if s[i..i+2] == "ana" then count = count + 1
end for
Print count
  1. A. 2
  2. B. 4
  3. C. 5
  4. D. 3

Correct answer: D. 3

Matches begin at positions 1, 3 and 5 of bananana, so the count is 3. Skipping past each match finds 2, counting the letter a gives 4, and also accepting nan finds 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic