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
Number of Distinct Substrings INPUT String s = "abc" 'a' 'b' 'c' i=0 i=1 i=2 All Substrings: "a" "b" "c" "ab" "bc" "abc" Length 1: 3 substrings Length 2: 2 substrings Length 3: 1 substring Total: 6 distinct ALGORITHM STEPS 1 Initialize Hash Set Store unique hash values 2 Rolling Hash Formula hash = hash*base + char 3 Generate All Substrings For each start position 4 Count Unique Hashes Return set size Rolling Hash Example base=31, mod=10^9+7 "a" ---> hash(1) "ab" --> hash(1*31+2) "abc" -> hash(33*31+3) Each hash is unique! FINAL RESULT Distinct Substrings Found: Hash Set Contents "a" [OK] "b" [OK] "c" [OK] "ab" [OK] "bc" [OK] "abc" [OK] Set Size = 6 OUTPUT 6 6 distinct substrings Key Insight: Rolling Hash computes substring hashes in O(1) time by extending previous hash values. This reduces time complexity from O(n^3) to O(n^2) by avoiding recomputation of common prefixes. TutorialsPoint - Number of Distinct Substrings in a String | Rolling Hash Optimization
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