Data Structures & AlgorithmsModerateTCS NQT · string round

Problem: How many distinct non-empty substrings does the string 'abab' contain?

Problem: How many distinct non-empty substrings does the string 'abab' contain?
s = 'abab'
print(len({s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)}))
What is printed?
  1. A. 7
  2. B. 6
  3. C. 8
  4. D. 10

Correct answer: A. 7

The distinct substrings are a, b, ab, ba, aba, bab and abab, so 7. Counting all 10 positional substrings ignores duplicates such as the two 'ab' and two 'a' occurrences.

More Coding Interview Problems questions

Exams that ask this topic