Number of Distinct Substrings
Count the distinct substrings of a string (the empty substring excluded).
Open on GeeksforGeeks ↗Intuition
Generating all n²/2 substrings and dropping them into a set works but costs O(n³) time once the string copying is counted. The reframing that fixes it: every substring is a prefix of some suffix. So insert all n suffixes into a trie, and each node below the root corresponds to exactly one distinct substring — the path from the root spells it out. Duplicates collapse onto shared paths automatically, so the answer is simply the node count, with no explicit de-duplication anywhere.
Approach
Every substring is a prefix of a suffix
Take any substring s[i..j]; it is a prefix of the suffix starting at i. So the set of all substrings equals the set of all prefixes of all suffixes.
Insert every suffix into a trie
For each start index, walk the suffix, creating nodes only where the path does not already exist.
Count nodes, not insertions
Each non-root node is one distinct substring. Repeated substrings reuse existing nodes and therefore add nothing.
Solution & live demo
Edge cases
Only n substrings exist ("a", "aa", "aaa") — the trie is one straight path of n nodes.
Nothing merges, so the count reaches the maximum n(n+1)/2.
Excluded by construction, since the root is not counted.