Distinct Echo Substrings

Hard

Topics
StringHash TableRolling Hash

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

a0b1c2a3b4c5a6b7c8
Input:  s = "abcabcabc"
Output: 3

Example 2

l0e1e2t3c4o5d6e7l8e9e10t11c12o13d14e15
Input:  s = "leetcodeleetcode"
Output: 2

Example 3

a0a1a2a3
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

  1. For every start index, try every half-length that fits twice within the string.
  2. Compare the two halves.
  3. On a match, add the half to a set.
  4. 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 counter

Complexity

  • 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 abc appearing 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 n comes from — and why the hashed version is faster.
  • Storing the whole echo a+a in 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)
SensAI
Beta
Tap the mic to stop voice mode