#1316

Distinct Echo Substrings

Hard
StringTrieRolling HashHash FunctionHash MapRolling Hash
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a rolling hash technique to efficiently check for distinct echo substrings. By hashing substrings, we can quickly determine if two substrings are equal without directly comparing them.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a rolling hash to generate hashes for all substrings of the input string.
  2. 2Step 2: For each substring, check if its length is even and if the first half matches the second half using the hash values.
  3. 3Step 3: Store unique valid hashes in a set to count distinct echo substrings.
solution.py19 lines
1def distinctEchoSubstrings(text):
2    MOD = 10**9 + 7
3    base = 31
4    n = len(text)
5    hashes = set()
6    power = [1] * (n + 1)
7    hash_value = 0
8
9    for i in range(n):
10        hash_value = (hash_value * base + (ord(text[i]) - ord('a') + 1)) % MOD
11        power[i + 1] = (power[i] * base) % MOD
12
13    for length in range(1, n // 2 + 1):
14        for start in range(n - 2 * length + 1):
15            hash1 = (hash_value - (hash_value - (ord(text[start]) - ord('a') + 1) * power[length]) % MOD + MOD) % MOD
16            hash2 = (hash_value - (hash_value - (ord(text[start + length]) - ord('a') + 1) * power[length]) % MOD + MOD) % MOD
17            if hash1 == hash2:
18                hashes.add(text[start:start + 2 * length])
19    return len(hashes)

Complexity note: The time complexity is O(n) because we compute hash values in linear time and check for distinct substrings using a set. The space complexity is O(n) due to the storage of hash values.

  • 1Understanding how to generate and check substrings is crucial.
  • 2Rolling hash can significantly reduce the time complexity of substring comparison.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.