Count Distinct Substrings
Count the different substrings of a string by putting all of its suffixes into a trie.
Given a string ss
Example 1
Output: 7
Explanation: a, b, ab, ba, aba, bab, abab.
Example 2
Output: 3
Explanation: a, aa, aaa.
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.
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>
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'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
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
- First, create an empty trie:
is a newroot , a small class whose arrayNode holds 26 links. Setnext to 0.count - Pick where each suffix starts with an outer loop, which moves
from 0 to the last position ofstart . For eachs , put the markerstart back oncur .root - Inside, a second loop moves
fromi to the end ofstart , and turns each character into its slots .c = s.charAt(i) - 'a' - If
iscur.next[c] , the substring fromnull tostart has not been seen before: create the node and add 1 toi . Then movecount tocur .cur.next[c] - After both loops have finished, return
as the number of different substrings.count
The main
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:
"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