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
Distinct Substring Counting ProcessStep 1: Input String"aba"Length: 3Max substrings: 3×4/2 = 6Step 2: Generate AllSubstrings (with duplicates):"", "a", "ab", "aba""b", "ba""a" (duplicate!)Step 3: Hash SetUnique substrings only:{"", "a", "b", "ab", "ba", "aba"}Count: 6Detailed Generation Processabai=0: Generate "a", "ab", "aba"i=1: Generate "b", "ba"i=2: Generate "a" (already exists)Final unique count: 6 + 1 (empty) = 6
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

n
2n
Quadratic Growth
Space Complexity
O(n²)

Store O(n²) hash values in the set, each taking O(1) space

n
2n
Quadratic Space

Constraints

  • 0 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only
  • Time limit: 2 seconds per test case
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~12 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen