Problem solution · Java

Number of Distinct Substrings in a String

Number of Distinct Substrings in a String: a Java solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Hash-based lookup
Source
walkccc LeetCode Solutions
Length
37 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Hash-based lookup

For Number of Distinct Substrings in a String, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 37 lines of Java from the credited upstream file 1698.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 3 loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeNumber of Distinct Substrings in a String · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int countDistinct(String s) {    final int n = s.length();    int ans = 0;    long[] pow = new long[n + 1];    // pow[i] := BASE^i    long[] hashes = new long[n + 1]; // hashes[i] := the hash of s[0..i)     pow[0] = 1;    for (int i = 1; i <= n; ++i) {      pow[i] = pow[i - 1] * BASE % HASH;      hashes[i] = (hashes[i - 1] * BASE + val(s.charAt(i - 1))) % HASH;    }     for (int length = 1; length <= n; ++length) {      Set<Long> seen = new HashSet<>();      for (int i = 0; i + length <= n; ++i)        seen.add(getHash(i, i + length, hashes, pow));      ans += seen.size();    }     return ans;  }   private static final int BASE = 26;  private static final int HASH = 1_000_000_007;   private static int val(char c) {    return c - 'a';  }   // Returns the hash of s[l..r).  private long getHash(int l, int r, long[] hashes, long[] pow) {    final long hash = (hashes[r] - hashes[l] * pow[r - l]) % HASH;    return hash < 0 ? hash + HASH : hash;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗