Distinct Echo Substrings
Hard
Topics
Return the number of distinct non-empty substrings of s that can be written as the concatenation of some string with itself (i.e. equal to a + a for some string a).
Example 1
Input: s = "abcabcabc" Output: 3
Example 2
Input: s = "leetcodeleetcode" Output: 2
Example 3
Input: s = "aaaa" Output: 2
Constraints
- 1 <= s.length <= 16
- s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A substring is an echo when it splits down the middle into two equal halves. So enumerate the candidates directly: pick a start and a half-length, compare the two halves, and keep the ones that match.
The deduplication detail is neat. The set stores the half rather than the whole echo, which is sound because distinct halves give distinct concatenations and vice versa — the map a → a+a is injective. Storing halves also keeps the keys shorter.
At the stated bound of 16 characters this brute force is the right answer. The real version of the problem, with much longer strings, is where rolling hashes or a suffix automaton earn their keep.
Approach
- For every start index, try every half-length that fits twice within the string.
- Compare the two halves.
- On a match, add the half to a set.
- Return the set's size.
Dry Run
s = "abcabcabc"
start half len first half second half match
0 3 abc abc yes
1 3 bca bca yes
2 3 cab cab yes
3 3 abc abc yes <- same half as start 0
distinct halves {abc, bca, cab} answer 3
"leetcodeleetcode" -> 2 the halves are "leetcodeleetcode"[:8] and "e"
the duplicate at start 3 is why a set is needed rather than a counterComplexity
- Time — O(n³): O(n²) start-and-length pairs, each comparing O(n) characters.
- Space — O(n²) distinct halves at worst, totalling O(n³) characters stored. Worth stating both numbers rather than just the entry count, since the strings are not constant size.
- With rolling hashes the comparison becomes O(1) and the whole thing is O(n²); a suffix automaton or Z-algorithm approach gets closer to O(n²) with no hashing risk.
Common Pitfalls
- Counting occurrences instead of distinct strings. The dry run shows
abcappearing as a half at two different starts; it must count once. - Enumerating all substrings and testing each for the echo property, which repeats the halving work and is easy to get wrong on odd lengths. Odd-length substrings can never be echoes, so iterating half-lengths skips them for free.
- Comparing with a slice in a loop and calling it O(1). String slicing copies, which is where the third factor of
ncomes from — and why the hashed version is faster. - Storing the whole echo
a+ain the set and then dividing the count. Harmless, but the injectivity argument is the thing worth stating. - Missing that the two halves may overlap in the original string. They cannot — they are adjacent by construction — but the related problem longest duplicate substring does allow overlap, and conflating the two is common.
- Reaching for hashing at
n <= 16. It adds collision risk for a speedup that is not needed; name it as the scaling answer and move on.
Full Solution — all languages
class Solution:
def distinctEchoSubstrings(self, s):
n = len(s)
seen = set()
for i in range(n):
length = 1
while i + 2 * length <= n:
a = s[i:i + length]
b = s[i + length:i + 2 * length]
if a == b:
seen.add(a)
length += 1
return len(seen)import java.util.*;
class Solution {
public int distinctEchoSubstrings(String s) {
int n = s.length();
Set<String> seen = new HashSet<>();
for (int i = 0; i < n; i++) {
for (int len = 1; i + 2 * len <= n; len++) {
String a = s.substring(i, i + len);
String b = s.substring(i + len, i + 2 * len);
if (a.equals(b)) seen.add(a);
}
}
return seen.size();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int distinctEchoSubstrings(string s) {
int n = s.size();
unordered_set<string> seen;
for (int i = 0; i < n; i++) {
for (int len = 1; i + 2 * len <= n; len++) {
string a = s.substr(i, len);
string b = s.substr(i + len, len);
if (a == b) seen.insert(a);
}
}
return (int) seen.size();
}
};/**
* @param {string} s
* @return {number}
*/ var distinctEchoSubstrings = function(s) {
const n = s.length;
const seen = new Set();
for (let i = 0; i < n; i++) {
for (let len = 1; i + 2 * len <= n; len++) {
const a = s.substring(i, i + len);
const b = s.substring(i + len, i + 2 * len);
if (a === b) seen.add(a);
}
}
return seen.size;
};