Data Structures & AlgorithmsModerateTCS NQT · string round

Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'?

Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'?
s = 'banana'
p = 'ana'
print(sum(1 for i in range(len(s) - len(p) + 1) if s[i:i + len(p)] == p))
What is printed?
  1. A. 1
  2. B. 3
  3. C. 4
  4. D. 2

Correct answer: D. 2

The occurrences start at index 1 and index 3, and they overlap at the shared 'a'. Non-overlapping counting would also give 1, which is the trap.

More Coding Interview Problems questions

Exams that ask this topic