AlgoInsight

DSA problem

Number of Distinct Substrings in a String

MediumString MatchingPattern: String Matchingtop600AmazonGoogleBloombergMicrosoft

Given a string s, return the number of distinct non-empty substrings of s. Two substrings are considered the same if and only if they are equal as strings.

A brute-force solution generates every substring and inserts each into a hash set, taking O(n³) time because substring construction is O(n) and there are O(n²) substrings. For modest inputs this works, but the elegant interview answer is to use a trie of suffixes.

The key insight is that every substring of s is a prefix of some suffix of s. So if we insert all n suffixes of s into a trie, every distinct prefix in the trie corresponds to exactly one distinct substring. Counting the number of distinct prefixes is the same as counting how many new nodes the trie ever creates, because each new node represents a substring we have not seen before.

The algorithm therefore inserts suffixes one by one, and each time a character forces the creation of a brand-new trie node, we increment the answer. The total work is O(n²) since every suffix has length up to n, and the space is also O(n²) in the worst case. This is the standard interview-grade trie approach and runs comfortably within the constraints.

Examples

Example 1
Input: s = "aabbaba"
Output: 21
Explanation: There are exactly 21 distinct non-empty substrings; the trie of suffixes creates 21 new nodes when inserting all suffixes one by one.
Example 2
Input: s = "abc"
Output: 6
Explanation: The distinct substrings are "a", "b", "c", "ab", "bc", "abc" — six of them.
Example 3
Input: s = "aaa"
Output: 3
Explanation: The distinct substrings are "a", "aa", and "aaa" — three of them.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringtriehash-table

Browse all DSA problems