Number of Distinct Substrings in a String - Problem
Given a string s, return the number of distinct substrings of s.
A substring is a contiguous sequence of characters within a string. For example, "abc" is a substring of "abcdef". Note that we need to count all possible substrings, including the empty string and the string itself, but each unique substring should only be counted once.
Example: For string "aba", the substrings are: "", "a", "b", "ab", "ba", "aba". Note that "a" appears twice but is only counted once.
Input & Output
example_1.py — Basic Case
$
Input:
s = "aba"
›
Output:
6
💡 Note:
The distinct substrings are: "", "a", "b", "ab", "ba", "aba". Note that "a" appears at positions 0 and 2, but is only counted once.
example_2.py — All Same Characters
$
Input:
s = "aaa"
›
Output:
4
💡 Note:
The distinct substrings are: "", "a", "aa", "aaa". Even though there are many overlapping substrings, we only count unique ones.
example_3.py — Single Character
$
Input:
s = "a"
›
Output:
2
💡 Note:
The distinct substrings are: "" (empty string) and "a". Total count is 2.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Initialize our 'index book' (hash set) and start with the empty entry
2
Generate
For each starting position, create all possible phrases (substrings) extending from that position
3
Check Duplicates
Before adding each phrase to our index, check if it already exists
4
Count Results
The final count in our index represents all unique substrings
Key Takeaway
🎯 Key Insight: Using a hash set automatically handles duplicate detection, making the algorithm simple yet efficient. The time complexity is dominated by the O(n²) substring generation, while space complexity depends on the number of unique substrings.
Time & Space Complexity
Time Complexity
O(n²)
O(n²) for nested loops, but each hash computation is O(1) with rolling hash
⚠ Quadratic Growth
Space Complexity
O(n²)
Store O(n²) hash values in the set, each taking O(1) space
⚠ Quadratic Space
Constraints
- 0 ≤ s.length ≤ 1000
- s consists of lowercase English letters only
- Time limit: 2 seconds per test case
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code