Count Distinct Substrings
Insert every suffix into a trie; count the new nodes
Every substring is a prefix of exactly one suffix of the string. Inserting all n suffixes into a trie maps each distinct substring onto exactly one node, because a trie merges shared prefixes onto the same path automatically. So instead of storing O(n^2) substrings in a hash set, insert every suffix and count how many BRAND NEW nodes get created along the way — that count is the answer. The empty prefix at the root is never counted.
Details
Animated on: Given a string, count the total number of distinct non-empty substrings it contains. Example: s = "aab".
Problem:Count Distinct SubstringsMedium
Insert every suffix into a trie; count the new nodes
step 1 / 11
s = "aab". A trie built from every suffix has exactly one node per distinct substring, so inserting each suffix and counting the BRAND NEW nodes created gives the answer.
1total <- 02root <- new node3FOR i <- 0 TO LENGTH(s) - 14 cur <- root5 FOR j <- i TO LENGTH(s) - 16 ch <- s[j]7 IF ch NOT IN cur.children8 cur.children[ch] <- new node9 total <- total + 110 cur <- cur.children[ch]11RETURN total
← / → step · space play · Home restart
Every step in words
Show all 11 steps
- s = "aab". A trie built from every suffix has exactly one node per distinct substring, so inserting each suffix and counting the BRAND NEW nodes created gives the answer.
- Suffix 1/3: "aab" (starts at index 0). Walk it down from the root, one character at a time.
- 'a' has no child here, so a new node "a" is created — substring "a" has never been seen before. Running total: 1.
- 'a' has no child here, so a new node "aa" is created — substring "aa" has never been seen before. Running total: 2.
- 'b' has no child here, so a new node "aab" is created — substring "aab" has never been seen before. Running total: 3.
- Suffix 2/3: "ab" (starts at index 1). Walk it down from the root, one character at a time.
- 'a' already exists as this child (node "a" was built by an earlier suffix), so we just follow the link — no new node, total stays 3.
- 'b' has no child here, so a new node "ab" is created — substring "ab" has never been seen before. Running total: 4.
- Suffix 3/3: "b" (starts at index 2). Walk it down from the root, one character at a time.
- 'b' has no child here, so a new node "b" is created — substring "b" has never been seen before. Running total: 5.
- Every suffix of "aab" is inserted. The trie ended up with 5 nodes below the root — one per distinct non-empty substring — so the answer is 5.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.