Number of Distinct Substrings
Implement countDistinctSubstrings
Given a string
s, count how many distinct (non-empty) substrings it has.
Every substring is a prefix of some suffix — specifically, the suffix that starts at the same position. So building a trie out of every suffix of s, one after another, means every distinct substring gets a node somewhere in that trie, and the trie's own structure prevents any duplicate from getting a second node: two suffixes that happen to share a prefix walk through the exact same existing nodes for as long as they agree. Counting how many nodes actually get freshly created — rather than reused — across all n suffix insertions gives the number of distinct substrings directly, without ever having to build a substring string, hash it, or check a set for membership.
Example 1:
Input: s = "ab"
Output: 3
Example 2:
Input: s = "aaa"
Output: 3
Example 3:
Input: s = "abc"
Output: 6
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 200 - ●
s consists of lowercase English letters
s =
ab