Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Count the distinct non-empty substrings of a short string.

Problem: Count the distinct non-empty substrings of a short string.
s = "ababa"
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. 15
  2. B. 10
  3. C. 8
  4. D. 9

Correct answer: D. 9

There are 15 substrings in total, but repeats collapse: the distinct ones are a, b, ab, ba, aba, bab, abab, baba, ababa, i.e. 9. For large n, a suffix automaton or suffix array does this in O(n) or O(n log n).

More Coding Interview Problems questions

Exams that ask this topic