Number of Distinct Substrings in a String Problem
#1698
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1698.
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.
Example 1:
Input: s = "aabbaba"
Output: 21
Explanation: The set of distinct strings is ["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"]
Example 2:
Input: s = "abcdefg"
Output: 28
Constraints:
1 <= s.length <= 500sconsists of lowercase English letters.
Follow up: Can you solve this problem in O(n) time complexity?
Solution
Approach: Enumerate Substrings in a Hash Set
Put every substring s[i..j] into a hash set; duplicates are stored only once, so the set's size is the number of distinct substrings. With n at most 500 there are about 125,000 substrings, which is small enough.
Complexity: O(n^3) time (each of the O(n^2) substrings takes O(n) to build and hash) and O(n^3) space for the stored strings, where n is the length of s.
class Solution:
def countDistinct(self, s: str) -> int:
n = len(s)
return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)})