Learn / Tries

Distinct substrings

Every substring is a prefix of some suffix. Insert every suffix of the string into a trie; each node then stands for exactly one distinct substring, so the number of nodes (without the root) is the answer.

How to recognise it

  • Count distinct substrings of a short string (up to a few thousand characters).
  • Questions about all substrings, where the same text should be counted once.
  • A quadratic method is acceptable.

Suffixes into a trie

count = 0
for i in 0..n-1:
    node = root
    for j in i..n-1:
        if node has no child s[j]: create it; count += 1
        node = node.child[s[j]]
return count

Add 1 if the problem also counts the empty substring. Suffix arrays and suffix automata do this faster, but the trie is the simplest correct method for small inputs. See the trie structure page.

Common mistakes

  • Counting every inserted character instead of only new nodes.
  • Forgetting whether the empty substring counts.

Problems

0 of 1 solved

Check yourself

Why does each trie node equal one distinct substring?

How many nodes can there be at most?

How many distinct non-empty substrings does 'aaaa' have?