Number of Distinct Substrings in a String - Problem
Given a string s, return the number of distinct substrings of s.
A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.
For example, if s = "abc", the substrings are: "a", "b", "c", "ab", "bc", "abc", and the empty string "". However, since we only count distinct substrings, duplicates are counted only once.
Input & Output
Example 1 — Simple String
$
Input:
s = "abc"
›
Output:
6
💡 Note:
The distinct substrings are: "a", "b", "c", "ab", "bc", "abc". Total count is 6.
Example 2 — Repeated Characters
$
Input:
s = "aaa"
›
Output:
3
💡 Note:
The distinct substrings are: "a", "aa", "aaa". Even though there are multiple 'a' characters, we only count unique substrings.
Example 3 — Single Character
$
Input:
s = "a"
›
Output:
1
💡 Note:
Only one substring possible: "a". Count is 1.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s = "abc"
2
Process
Generate all substrings and count unique ones
3
Output
Return count = 6
Key Takeaway
🎯 Key Insight: Use a hash set to automatically eliminate duplicate substrings while counting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code