Distinct Echo Substrings - Problem

Given a string text, find the number of distinct echo substrings.

An echo substring is a non-empty substring that can be written as the concatenation of some string with itself. In other words, it can be written as a + a where a is some string.

Example: In the string "abcabc", the substring "abcabc" is an echo substring because it equals "abc" + "abc". Similarly, "aa" is an echo substring in "baab" because it equals "a" + "a".

Your task is to count how many distinct echo substrings exist in the given text. Two echo substrings are considered the same if they have identical characters in the same order.

Input & Output

example_1.py โ€” Basic Echo Pattern
$ Input: text = "abcabc"
โ€บ Output: 2
๐Ÿ’ก Note: The echo substrings are "abcabc" (abc+abc) and any repeated single characters if they exist. In this case, we have "abcabc" as one echo substring.
example_2.py โ€” Multiple Patterns
$ Input: text = "aabaaba"
โ€บ Output: 4
๐Ÿ’ก Note: The echo substrings are: "aa" (a+a), "aaba" (aa+ba), "baab" (ba+ab), and "aabaaba" (aaba+aaba). Each represents a unique echo pattern.
example_3.py โ€” No Echo Patterns
$ Input: text = "abcd"
โ€บ Output: 0
๐Ÿ’ก Note: No substring can be split into two identical halves, so there are no echo substrings.

Visualization

Tap to expand
๐Ÿ” Echo Substring Detection Processa b c a b c1Start2Expand3Hash4Verify5StoreLeft Half: "abc"Hash: 12345Right Half: "abc"Hash: 12345โœ“Echo Found: "abcabc"
Understanding the Visualization
1
Scan Position
Choose a starting position in the string
2
Expand Outward
Gradually expand to form potential echo substrings
3
Hash Comparison
Use rolling hash to quickly compare halves
4
Verify Match
Confirm the echo pattern with actual string comparison
5
Store Result
Add distinct echo substrings to result set
Key Takeaway
๐ŸŽฏ Key Insight: Rolling hash allows us to compare substring halves in O(1) time, making echo detection much more efficient than naive string comparison.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

O(n) positions ร— O(n) expansions, but with O(1) hash comparisons

n
2n
โš  Quadratic Growth
Space Complexity
O(nยฒ)

Storing distinct echo substrings in the set

n
2n
โš  Quadratic Space

Constraints

  • 1 โ‰ค text.length โ‰ค 2000
  • text consists of lowercase English letters only
  • Echo substring must have even length (since it's a+a)
  • All substrings must be non-empty
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
31.6K Views
Medium Frequency
~25 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