Count Distinct Substrings

Count the different substrings of a string by putting all of its suffixes into a trie.

Given a string s of lowercase letters, return how many different non-empty substrings it has. A substring is a run of consecutive characters of s, and substrings that read the same are counted once.

Example 1
Input: s = "abab"
Output: 7
Explanation: a, b, ab, ba, aba, bab, abab.
Example 2
Input: s = "aaa"
Output: 3
Explanation: a, aa, aaa.
Solution

The Idea

Take the word abab and write down every piece you can cut out of it without skipping a letter. Starting at the first a you get a, ab, aba and abab. Starting at the first b you get b, ba and bab. Starting at the second a you get a and ab, and starting at the last b, just b.

That is 10 substrings, but a, ab and b each appear twice, so only 7 are different. Example 2 shows the gap even more clearly: aaa has 6 substrings and only 3 different ones, a, aa and aaa. How can we count each different substring once, without writing them all out and comparing every one with every other?

Look at how the list above was made. Each starting point gives a row that grows to the right until the word ends. The first row, a, ab, aba, abab, holds the beginnings of abab, and the second row holds the beginnings of bab. A piece that runs to the end of the word is called a suffix, and a beginning of a piece is called a prefix. Every substring starts somewhere, so it is a prefix of the suffix that starts at the same place.

Now store the suffixes so that beginnings they share are stored once. Look at the picture below. From the circle labelled root, where every suffix starts, a link labelled a leads to a box for the substring a. From there a link labelled b leads on to ab, and so on to abab. The suffix bab starts a second branch, through the link b, with the boxes b, ba and bab.

The trie of all suffixes of abab. From the root, the link a leads to the boxes a, ab, aba and abab, made by the suffix abab. The link b leads to the boxes b, ba and bab, made by the suffix bab. The suffix ab walks the existing links a and b, shown in orange, and makes no new box. Seven boxes stand for the seven distinct substrings.

Each box is called a node, and reading the letters on the links from the root down to a node spells the text written in it. This shape, where each link carries one letter and strings with the same beginning share a path, is called a trie. Here it holds the suffixes of abab, and every node below the root marks the end of one substring.

The last two suffixes add nothing. The suffix ab follows the orange links a and b, which already exist, and the suffix b follows the existing link b. Two equal substrings always spell the same path, so they end at the same node. That is why the picture shows "7 nodes = 7 substrings".

So counting different substrings becomes counting nodes. And a node is new exactly when inserting a suffix has to create it, so the count can grow while the suffixes go in, with no comparing at all.

Solution Approach

Turning that idea into code means four decisions: whether a plain set of strings would do, how a node keeps its links, how each suffix goes in, and which steps add to the count.

A set of strings

Why not put every substring into a HashSet<String> and return its size? It gives the right answer, but a string of n letters has n(n + 1)/2 substrings, about 500,000 for 1,000 letters. Each one is copied and hashed letter by letter, so the work grows like n3. The trie looks at each letter of each suffix once, which is n(n + 1)/2 steps in all.

How a node keeps its links

What does a node need to hold? Only its outgoing links, at most one per letter. The letters are lowercase, so an array of 26 slots is enough: slot 0 for a, slot 1 for b, up to slot 25 for z. Subtracting 'a' from a character gives its slot, and an empty slot holds null.

Inserting the suffixes

Where does each insert begin? Every suffix starts at the root and goes into the same trie, the longest one first. A marker named cur follows the suffix one letter at a time. If the link for the next letter exists, the marker moves along it; if not, a new node is made first and then the marker moves.

Which steps add to the count

Should every step of a walk add to the count? No, only a step that creates a node. In the picture, the suffix ab walks two links and creates nothing, because the nodes a and ab were counted when abab went in. Counting every step would count each substring as often as it appears: 10 for abab instead of 7. The root is never counted, so the empty string gives 0.

Java Solution

The method countDistinct works in these steps:

  1. First, create an empty trie: root is a new Node, a small class whose array next holds 26 links. Set count to 0.
  2. Pick where each suffix starts with an outer loop, which moves start from 0 to the last position of s. For each start, put the marker cur back on root.
  3. Inside, a second loop moves i from start to the end of s, and turns each character into its slot c = s.charAt(i) - 'a'.
  4. If cur.next[c] is null, the substring from start to i has not been seen before: create the node and add 1 to count. Then move cur to cur.next[c].
  5. After both loops have finished, return count as the number of different substrings.

The main method runs both examples, a string with no repeated letter, the word banana, a single letter and the empty string.

Java
public class CountDistinctSubstrings {

    private static class Node {
        Node[] next = new Node[26];           // one slot per letter, 'a' to 'z'
    }

    public static int countDistinct(String s) {
        Node root = new Node();
        int count = 0;
        for (int start = 0; start < s.length(); start++) {
            Node cur = root;                  // insert the suffix that begins at start
            for (int i = start; i < s.length(); i++) {
                int c = s.charAt(i) - 'a';
                if (cur.next[c] == null) {
                    cur.next[c] = new Node();
                    count++;                  // a new node: a substring not seen before
                }
                cur = cur.next[c];
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String[] tests = {"abab", "aaa", "abc", "banana", "z", ""};
        for (String s : tests) {
            System.out.println("\"" + s + "\" -> " + countDistinct(s));
        }
    }
}

Running it prints:

Output
"abab" -> 7
"aaa" -> 3
"abc" -> 6
"banana" -> 15
"z" -> 1
"" -> 0

The lines for abab and aaa give 7 and 3, the answers of the two examples. In abc no letter repeats, so every one of its 6 substrings is different and each makes its own node.

Look at the banana line: 15. The word has 21 substrings, but a appears three times and n, an, na and ana twice each, so 6 of them land on nodes that already exist. The last line shows the empty string: the outer loop never runs, only the root exists, and the root is not counted.

Complexity

The work is one walk per suffix, and the memory is one node per different substring.

  • Time: O(n2), because the n suffixes of a string of n letters hold n(n + 1)/2 letters in total, and each letter costs one array lookup and at most one new node.
  • Space: O(n2), because the trie keeps one node per different substring, up to n(n + 1)/2 nodes when nothing repeats, as in abc, and each node carries its own 26-slot array.

For a trie that stores whole words, with insert and search, see Implement Trie.