Number of Distinct Substrings
Number of Distinct Substrings is a GFG problem (Medium). Given a string s of lowercase letters, return how many different non-empty substrings it has.
- A substring is a block of consecutive letters of
s. - Equal substrings count once, even when they sit at different positions.
A string of 3,000 letters has about 4.5 million substrings, so the method has to spend O(1) work on each one instead of copying it.
- 1 <= |s| <= 3000
- s consists of lowercase English letters.
- The empty substring is not counted.
Intuition
Every substring is a prefix of some suffix: s[i..j] is the first few letters of the suffix that starts at i. A trie stores prefixes, one node per prefix, so put all n suffixes into one trie and watch which steps create nodes.
- New node: no earlier suffix spelled these letters, so this substring is new. Count it.
- Existing node: an earlier suffix starts the same way, so this substring was already counted. Just step into it.
The letters on the path from the root spell the node's substring, so two nodes never spell the same string. The answer is the number of nodes below the root, with no set and no string comparison.
"How many different substrings" means removing duplicates among all prefixes of all suffixes. A trie, a sorted suffix list or a suffix automaton does that by sharing structure, so no two substrings are ever compared letter by letter.
Approach
Before reading on, write s[i..j] as a prefix of one suffix of s. Then pick a structure where two equal prefixes land on the same spot, so the second one costs nothing to recognise. Aim for O(n²) steps of O(1) each.
Start with an empty trie
Create a root with no children and set count = 0. The root stands for the empty substring, which this problem does not count, so it is never added to count.
Walk every suffix in from the root
For each start index i, begin at the root and read s[i], s[i+1], and so on to the end of the string. Each step down spells a substring one letter longer, so this single walk meets every substring that starts at i.
Create a node only when the letter is missing
If the current node has no child for the letter, create one and add 1 to count, because no earlier walk spelled this substring. Then step into the child, whether it is new or old, and read the next letter.
Return the count
After the last suffix, count equals the number of nodes below the root. Each of those nodes is one distinct substring, so count is the answer and the trie never needs a second pass.
Code in Python, C++ and Java
Common pitfalls
Counting every step instead of every new node
node = node.setdefault(ch, {})
count += 1if ch not in node:
node[ch] = {}
count += 1
node = node[ch]Adding 1 on every step counts each substring once per position, so "aaa" returns 6 instead of 3. Only a step that has to create a node meets a substring for the first time.
Adding 1 for the empty substring
return count + 1
return count
Some versions of this problem count "" as a substring and add 1 at the end. This one does not, so "aaa" must give 3, not 4. Check the problem's own example before adding it.
Putting every substring into a set
return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)})count new trie nodes while walking each suffix
The answer is right, but each substring is copied and hashed letter by letter. For a 3,000-letter string with few repeats, the set ends up holding billions of letters, far past the time and memory limits.
Edge cases
"z"One walk, one new node, answer 1. The root is never counted, so the empty substring stays out.
"aaaa"The first walk builds one chain of 4 nodes and every later walk only follows it, so the answer is 4: the smallest possible for that length.
Complexity
Number of Distinct Substrings FAQ
Is this the same problem as Number of Distinct Substrings in a String?
Yes. LeetCode 1698 asks for the same count, also without the empty substring, under the method name countDistinct. Its follow-up asks for O(n) time, which needs a suffix automaton: the answer is the sum, over its states, of each state's length minus the length of its suffix link.
Can you count distinct substrings without building a trie?
Yes, with sorted suffixes. Sort the n suffixes; each one adds its length minus the length of its common prefix with the suffix before it, because those shared prefixes were counted already. For "aba" the sorted suffixes are a, aba, ba, giving 1 + (3 − 1) + 2 = 5. This keeps memory near O(n) when the trie would grow too large.