Number of Distinct Substrings in a String

Pattern: Distinct substrings

medium

Every substring is a prefix of a suffix. Insert every suffix into a trie; each new node is a substring not seen before, so the number of nodes created is the answer.

The problem

Return the number of distinct non-empty substrings of s.

Think first

  • Where does every substring appear in the suffixes?
  • When is a substring new?
  • How many nodes can there be?

Hints

    Brute force, and why it fails

    Put every substring in a hash set: O(n³) time for the copies.

    The key insight

    Shared prefixes of suffixes share trie nodes, so each distinct substring is counted once without building it.

    Dry run

    aabbaba: 7 single letters give 2 distinct (a, b).

    Step 1 of 2

    The plan

    count = 0
    for i: node = root; for j from i: if no child s[j]: create, count += 1; move down
    return count
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Every (start, end) pair once.

    Edge cases

    • All equal letters: n.
    • All different: n(n + 1) / 2.
    • One letter: 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int countDistinct(String s) {
            List<int[]> next = new ArrayList<>();   // a trie of every suffix; each node is one distinct substring
            next.add(new int[26]);
            for (int i = 0; i < s.length(); i++) {
                int n = 0;
                for (int j = i; j < s.length(); j++) {   // s[i..j] for every j, all on one path
                    int c = s.charAt(j) - 'a';
                    if (next.get(n)[c] == 0) {
                        next.get(n)[c] = next.size();
                        next.add(new int[26]);
                    }
                    n = next.get(n)[c];
                }
            }
            return next.size() - 1;                 // every node but the root
        }
    }

    C++

    class Solution {
    public:
        int countDistinct(string s) {
            vector<vector<int>> next(1, vector<int>(26, 0));   // a trie of every suffix; each node is one distinct substring
            for (size_t i = 0; i < s.size(); i++) {
                int n = 0;
                for (size_t j = i; j < s.size(); j++) {   // s[i..j] for every j, all on one path
                    int c = s[j] - 'a';
                    if (next[n][c] == 0) {
                        next[n][c] = static_cast<int>(next.size());
                        next.push_back(vector<int>(26, 0));
                    }
                    n = next[n][c];
                }
            }
            return static_cast<int>(next.size()) - 1;   // every node but the root
        }
    };

    Python

    class Solution:
        def countDistinct(self, s: str) -> int:
            root, count = {}, 0                     # a trie of every suffix; each node is one distinct substring
            for i in range(len(s)):
                node = root
                for c in s[i:]:                     # s[i..j] for every j, all on one path
                    if c not in node:
                        node[c] = {}
                        count += 1                  # a new node is a substring not seen before
                    node = node[c]
            return count

    Common mistakes

    • Counting the empty substring when not asked.
    • Creating a substring copy for each pair.

    Similar problems