Distinct Echo Substrings Problem
Description
LeetCode Problem 1316.
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
Constraints:
1 <= text.length <= 2000texthas only lowercase English letters.
Solution
Approach: Common Prefixes Along Diagonals
A substring of length 2L starting at i is an echo when its two halves match, that is, when text[i..i + L - 1] equals text[i + L..i + 2L - 1]. In other words, the suffixes starting at i and at i + L share a common prefix of length at least L.
Common prefix lengths for a fixed shift L are easy to get for all i at once. Walk i from right to left with a counter run: if text[i] == text[i + L], then run grows by one, otherwise it drops to 0. After the step for i, run is the length of the common prefix of text[i:] and text[i + L:]. So (i, L) is an echo exactly when run >= L.
That finds every echo occurrence, but the problem counts distinct strings: in "aaaa", "aa" occurs three times and counts once. We count each echo only at its first occurrence. A substring text[i..i + 2L - 1] has appeared before if, for some j < i, the suffixes at j and i share at least 2L characters. So precompute seen[i], the longest common prefix of text[i:] with any earlier suffix, by running the same right-to-left counter on every shift d = 1 .. n - 1 and keeping the maximum for each position. Then (i, L) is new exactly when seen[i] < 2L.
This is exact: no hashing, so no risk of two different strings being mistaken for the same one. For "abcabcabc", the echoes with L = 3 start at 0, 1, 2 and 3; the one at 3 is "abcabc" again (seen[3] = 6), so the answer is 3.
Complexity: O(n2) time for a text of length n, as both passes walk O(n) positions for each of O(n) shifts; O(n) extra space.
class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
n = len(text)
# seen[i]: the length of the longest prefix of text[i:] that also starts at some earlier index.
# Walking each diagonal (j, j + d) from the right, run is the length of the common prefix of text[j:] and text[j + d:].
seen = [0] * n
for d in range(1, n):
run = 0
for j in range(n - d - 1, -1, -1):
if text[j] == text[j + d]:
run += 1
if run > seen[j + d]:
seen[j + d] = run
else:
run = 0
count = 0
for half in range(1, n // 2 + 1):
run = 0 # common prefix of text[i:] and text[i + half:]
for i in range(n - half - 1, -1, -1):
run = run + 1 if text[i] == text[i + half] else 0
# text[i : i + 2 * half] is an echo, and this is its first occurrence.
if run >= half and seen[i] < 2 * half:
count += 1
return count