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
Count Distinct Substrings: "abc" → 6Input String"abc"Extract"a""b""c""ab""bc""abc"All Distinct SubstringsCountResult6
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
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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