Distinct Echo Substrings - Problem

Given a string text, return the number of distinct non-empty substrings that can be written as the concatenation of some string with itself.

In other words, count all substrings that can be written as a + a where a is some non-empty string.

For example, if text = "abcabc", then "abcabc" can be written as "abc" + "abc", so it counts as an echo substring.

Input & Output

Example 1 — Basic Case
$ Input: text = "abab"
Output: 1
💡 Note: Only "abab" is an echo substring ("ab" + "ab"). The substring "ab" by itself is not an echo since "a" ≠ "b".
Example 2 — Longer String
$ Input: text = "aabaaba"
Output: 2
💡 Note: Echo substrings: "aa" appears at multiple positions but counts once, and "aabaab" ("aab" + "aab").
Example 3 — No Echoes
$ Input: text = "a"
Output: 0
💡 Note: Single character cannot form an echo substring (need at least length 2)

Constraints

  • 1 ≤ text.length ≤ 2000
  • text consists of lowercase English letters only

Visualization

Tap to expand
Distinct Echo Substrings Rolling Hash Optimization Approach INPUT String: text a idx 0 b idx 1 a idx 2 b idx 3 Input Value text = "abab" Echo Format: a + a Substrings to check: "aa" = "a" + "a" "abab" = "ab" + "ab" "bb" = "b" + "b" (and more...) ALGORITHM STEPS 1 Precompute Hash Calculate rolling hash for all prefixes 2 For Each Even Length Try lengths 2, 4, 6... up to n 3 Compare Halves hash(first half) == hash(second half)? 4 Store in HashSet Add valid echoes to avoid duplicates Rolling Hash Check "abab" len=4 ab ab OK Match! "ab" len=2 a b No Match FINAL RESULT Distinct Echo Substrings Found Echo #1: "abab" = "ab" + "ab" Echo #2: "aa" (not in text) Note: "aa" would be valid but doesn't exist in "abab" OUTPUT 2 OK - 2 distinct echoes Key Insight: Rolling Hash allows O(1) substring comparison by precomputing prefix hashes. For a string of length 2k, we check if hash(0..k-1) == hash(k..2k-1). Using a HashSet ensures we count only distinct echo substrings. Time Complexity: O(n^2) with constant-time hash comparisons instead of O(n) string matching. TutorialsPoint - Distinct Echo Substrings | Rolling Hash Optimization
Asked in
Google 15 Facebook 12
23.4K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen