Data Structures & AlgorithmsHardICPC regional · string round

Problem: What is the length of the longest substring of 'banana' that occurs at least twice (occurrences may overlap)? Run the code.

Problem: What is the length of the longest substring of 'banana' that occurs at least twice (occurrences may overlap)? Run the code.
s = 'banana'
best = 0
for L in range(1, len(s)):
    subs = [s[i:i + L] for i in range(len(s) - L + 1)]
    if any(subs.count(x) >= 2 for x in subs):
        best = L
print(best)
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 1

Correct answer: A. 3

'ana' occurs at indices 1 and 3 (overlapping at the shared a), and no length-4 substring repeats. Non-overlapping counting would give a different answer.

More Coding Interview Problems questions

Exams that ask this topic