Data Structures & AlgorithmsModerateTCS NQT · string counting

Problem: For the string 'mississippi', what is the number of distinct substrings of length 2 that occur at least twice? Run the code.

Problem: For the string 'mississippi', what is the number of distinct substrings of length 2 that occur at least twice? Run the code.
from collections import Counter
s = 'mississippi'
c = Counter(s[i:i + 2] for i in range(len(s) - 1))
print(sum(1 for v in c.values() if v >= 2))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: C. 3

The length-2 substrings are mi, is, ss, si, is, ss, si, ip, pp, pi; the repeated ones are is (2), ss (2) and si (2), so 3 values have count at least 2.

More Coding Interview Problems questions

Exams that ask this topic