GeeksforGeeks Medium

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.

Constraints
  • 1 <= |s| <= 3000
  • s consists of lowercase English letters.
  • The empty substring is not counted.
triestringsuffix
Open on GeeksforGeeks ↗
02

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 to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def countSubs(self, s):
▶3 root = {}
▶4 count = 0
▶5 for i in range(len(s)):
▶6 node = root
▶7 for j in range(i, len(s)):
▶8 ch = s[j]
▶9 if ch not in node:
▶10 node[ch] = {}
▶11 count += 1
▶12 node = node[ch]
▶13 return count
a0b1a2b3a4distinct0rootempty trie, count 0
s"ababa"5 letters
count0
The trie starts with only its root, which stands for the empty substring. The problem does not count that one, so the counter starts at 0. Each suffix of ababa will now be walked into the trie, one letter at a time.
a0startb1a2b3a4distinct1roota'a' is new → count 1
suffix"ababa"starts at 0
substring"a"no node yet
count1
New suffix ababa starts at index 0, so the walk begins at the root again. No earlier suffix went down this path, so a has never been spelled before. Create the node and count it: 1 distinct so far.
a0startb1a2b3a4distinct2rootab'ab' is new → count 2
suffix"ababa"starts at 0
substring"ab"no node yet
count2
No earlier suffix went down this path, so ab has never been spelled before. Create the node and count it: 2 distinct so far.
a0startb1a2b3a4distinct3rootaba'aba' is new → count 3
suffix"ababa"starts at 0
substring"aba"no node yet
count3
No earlier suffix went down this path, so aba has never been spelled before. Create the node and count it: 3 distinct so far.
a0startb1a2b3a4distinct4rootabab'abab' is new → count 4
suffix"ababa"starts at 0
substring"abab"no node yet
count4
No earlier suffix went down this path, so abab has never been spelled before. Create the node and count it: 4 distinct so far.
a0startb1a2b3a4distinct5rootababa'ababa' is new → count 5
suffix"ababa"starts at 0
substring"ababa"no node yet
count5
No earlier suffix went down this path, so ababa has never been spelled before. Create the node and count it: 5 distinct so far.
a0b1starta2b3a4distinct6rootababab'b' is new → count 6
suffix"baba"starts at 1
substring"b"no node yet
count6
New suffix baba starts at index 1, so the walk begins at the root again. No earlier suffix went down this path, so b has never been spelled before. Create the node and count it: 6 distinct so far.
a0b1starta2b3a4distinct7rootabababa'ba' is new → count 7
suffix"baba"starts at 1
substring"ba"no node yet
count7
No earlier suffix went down this path, so ba has never been spelled before. Create the node and count it: 7 distinct so far.
a0b1starta2b3a4distinct8rootabababab'bab' is new → count 8
suffix"baba"starts at 1
substring"bab"no node yet
count8
No earlier suffix went down this path, so bab has never been spelled before. Create the node and count it: 8 distinct so far.
a0b1starta2b3a4distinct9rootababababa'baba' is new → count 9
suffix"baba"starts at 1
substring"baba"no node yet
count9
No earlier suffix went down this path, so baba has never been spelled before. Create the node and count it: 9 distinct so far.
a0b1a2startb3a4distinct9rootababababa'a' seen before → follow it
suffix"aba"starts at 2
substring"a"node exists
count9
New suffix aba starts at index 2, so the walk begins at the root again. The node for a is already there, because an earlier suffix starts with the same letters. That substring was counted then, so step into the node and add nothing.
a0b1a2startb3a4distinct9rootababababa'ab' seen before → follow it
suffix"aba"starts at 2
substring"ab"node exists
count9
The node for ab is already there, because an earlier suffix starts with the same letters. That substring was counted then, so step into the node and add nothing.
a0b1a2startb3a4distinct9rootababababa'aba' seen before → follow it
suffix"aba"starts at 2
substring"aba"node exists
count9
The node for aba is already there, because an earlier suffix starts with the same letters. That substring was counted then, so step into the node and add nothing.
a0b1a2b3starta4distinct9rootababababa'b' seen before → follow it
suffix"ba"starts at 3
substring"b"node exists
count9
New suffix ba starts at index 3, so the walk begins at the root again. The node for b is already there, because an earlier suffix starts with the same letters. That substring was counted then, so step into the node and add nothing.
a0b1a2b3starta4distinct9rootababababa'ba' seen before → follow it
suffix"ba"starts at 3
substring"ba"node exists
count9
The node for ba is already there, because an earlier suffix starts with the same letters. That substring was counted then, so step into the node and add nothing.
a0b1a2b3a4startdistinct9rootababababa'a' seen before → follow it
suffix"a"starts at 4
substring"a"node exists
count9
New suffix a starts at index 4, so the walk begins at the root again. The node for a is already there, because an earlier suffix starts with the same letters. That substring was counted then, so step into the node and add nothing.
a0b1a2b3a4distinct9rootababababa9 nodes below the root → answer 9
count9nodes below the root
Every suffix is in. Each node spells one substring (read the letters from the root down to it), and two nodes never spell the same one. So the 9 nodes are exactly the distinct non-empty substrings of ababa, out of 15 substrings counted with repeats.
05

Common pitfalls

Counting every step instead of every new node

✗ Wrong
node = node.setdefault(ch, {})
count += 1
✓ Right
if 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

✗ Wrong
return count + 1
✓ Right
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

✗ Wrong
return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)})
✓ Right
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.

06

Edge cases

One letter, e.g. "z"

One walk, one new node, answer 1. The root is never counted, so the empty substring stays out.

Every letter the same, e.g. "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.

07

Complexity

Time
O(n²)
Space
O(n²)
The n suffixes hold n(n+1)/2 letters in total, and each letter is one O(1) step in the trie. Every step can create a node, so a 3,000-letter string with few repeats builds about 4.5 million nodes. That is why the C++ and Java code store children as arrays of 26 integers in one list rather than as separate objects.
08

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.