Pattern visualizer
Number of Distinct Substrings in String
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. Animated on: Given a string, count the total number of distinct non-empty substrings it contains. Example: s = "aab"..
Insert every suffix into a trie; count the new nodes
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