Data Structures & AlgorithmsModerateTCS NQT · string basics

Problem: What is the length of the longest run of equal consecutive characters in 'aabbbbcc'? Run the code.

Problem: What is the length of the longest run of equal consecutive characters in 'aabbbbcc'? Run the code.
s = 'aabbbbcc'
best = cur = 1
for i in range(1, len(s)):
    cur = cur + 1 if s[i] == s[i - 1] else 1
    best = max(best, cur)
print(best)
What is printed?
  1. A. 3
  2. B. 5
  3. C. 2
  4. D. 4

Correct answer: D. 4

cur grows while a character repeats and resets to 1 when it changes, so the runs are aa (2), bbbb (4) and cc (2), and best is 4. Resetting cur to 0 instead of 1 undercounts every run by one and prints 3.

More Coding Interview Problems questions

Exams that ask this topic