Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1316: Distinct Echo Substrings

In this guide, we solve Leetcode #1316 Distinct Echo Substrings in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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).

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Trie, String, Hash Function, Rolling Hash

Intuition

Prefix queries are most efficient with a trie.

Each character transitions to the next node in the tree.

Approach

Insert words into the trie and traverse by characters for queries.

Track terminal markers to distinguish full words from prefixes.

Steps:

  • Build the trie.
  • Traverse for each query.
  • Return matches or validations.

Example

Input: text = "abcabcabc" Output: 3 Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".

Python Solution

class Solution: def distinctEchoSubstrings(self, text: str) -> int: def get(l, r): return (h[r] - h[l - 1] * p[r - l + 1]) % mod n = len(text) base = 131 mod = int(1e9) + 7 h = [0] * (n + 10) p = [1] * (n + 10) for i, c in enumerate(text): t = ord(c) - ord('a') + 1 h[i + 1] = (h[i] * base) % mod + t p[i + 1] = (p[i] * base) % mod vis = set() for i in range(n - 1): for j in range(i + 1, n, 2): k = (i + j) >> 1 a = get(i + 1, k + 1) b = get(k + 2, j + 1) if a == b: vis.add(a) return len(vis)

Complexity

The time complexity is O(total characters). The space complexity is O(total characters).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy