Problem 1316

Abstract / Summary

Count unique substrings that repeat twice in a row in the given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1316.cpp

class Solution {
public:
    int distinctEchoSubstrings(string text) {
        unordered_set<string> found;

        for (int length = 1; length <= text.size() / 2; length++)
        {
            for (int pos = 0; pos + 2*length <= text.size(); pos++)
            {
                // optimization
                if (text[pos + length - 1] != text[pos + length + length - 1])
                    continue;

                bool ok = true;
                for (int i = pos; i < pos + length - 1; i++) // -1 => opt
                    if (text[i] != text[i + length])
                    {
                        ok = false;
                        break;
                    }

                if (ok)
                    found.insert(text.substr(pos, length));
            }
        }

        return found.size();
    }
};
29 lines | 856 bytes | submitted August 10, 2023 | GitHub   8% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (40k+ submissions).

Typical patterns to solve this problem:
  • Hash Function
  • Rolling Hash
  • String
  • Trie
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation defines a method that receives a string and returns the number of distinct substrings that appear consecutively twice - an “echo” substring. The algorithm enumerates possible lengths for the repeated block, slides a window across the text, verifies that the two halves are identical, and records each unique block in a hash-based container. The final answer is the cardinality of that container.

Main Algorithm

The outermost structure iterates over all feasible half-lengths. The loop stops at half of the string length because a longer block could not be duplicated within the original string.

for (int length = 1; length <= text.size() / 2; length++)
{
    for (int pos = 0; pos + 2*length <= text.size(); pos++)
    {
        // inner work
    }
}

Inside the inner loop the code first checks a single character at the boundary of the two candidate halves. If the characters differ, the two halves cannot be equal, and the iteration is skipped.

if (text[pos + length - 1] != text[pos + length + length - 1])
    continue;

When the boundary characters match, a detailed comparison of the two halves is performed. The loop runs from the start of the first half up to the penultimate character, because the last character has already been compared by the previous optimization. If any mismatch is found, a flag is cleared and the loop exits early.

bool ok = true;
for (int i = pos; i < pos + length - 1; i++) // -1 => opt
    if (text[i] != text[i + length])
    {
        ok = false;
        break;
    }

If the flag remains true, the substring representing the first half is extracted and inserted into an unordered set that automatically discards duplicates.

if (ok)
    found.insert(text.substr(pos, length));

After all lengths and positions have been examined, the size of the set is returned, representing the count of distinct echo substrings.

return found.size();

Edge Cases Handled

When the input string is empty or has length one, the outer length loop never executes because the maximum half length is zero. Consequently, the set remains empty and the method correctly returns zero.

If the string contains no pair of identical adjacent blocks, the inner verification never succeeds, and the set stays empty, again yielding a zero result.

For strings composed of a single repeated character, such as "aaaaa", the algorithm still distinguishes different block lengths. Each length that satisfies the duplication condition contributes a distinct entry to the set, because the extracted substring differs in length even though the characters are identical.

When the string ends with a partial block that cannot be paired, the condition pos + 2*length <= text.size() prevents the inner loop from accessing out-of-range indices, ensuring safe termination without extra checks.

Performance Optimizations

The most noticeable optimization is the early character comparison at the boundary of the two halves. By discarding positions where the last character of the first half differs from the last character of the second half, the algorithm avoids the more expensive full-block comparison for a large fraction of candidates.

The inner verification loop stops as soon as a mismatch is detected, rather than scanning the entire block. This early exit reduces work for non-matching windows.

The loop bound i < pos + length - 1 deliberately omits the final character, because it has already been compared in the boundary check. This saves one comparison per successful candidate.

Using an unordered_set for storage provides average constant-time insertion and lookup, which keeps the overhead of duplicate detection low even when many substrings are examined.

Finally, the call to text.substr(pos, length) is performed only after the full equality test succeeds, preventing unnecessary allocation of temporary strings for windows that are later discarded.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long train made of colored blocks, and you want to find pairs of identical cars that are touching each other. Think of the code as a very clever detective looking at the train.

First, the detective picks a size for the cars, starting with a size of one block and getting bigger until the train cannot be split into two equal parts anymore. For each size, the detective looks at every possible spot along the train to see if there is a group of blocks that repeats itself immediately.

If the detective finds a spot where a group of blocks is followed by an exact copy of the same group, that matches the rule of an echo. The detective uses a special magic box to keep track of these echoes. Every time a new echo is found, it gets placed into the box, but if the detective finds an echo they have already seen before, the box is smart enough to just keep the one instead of adding it again. This way, the box only holds unique echoes. The detective keeps checking every single spot until there is nothing left to explore, making sure every possible hidden echo is safely inside the collection.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.48 | σ = 1.40

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python Rust
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lzl124631x C++
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lzl124631x C++
suxrobGM C#
wisdompeak C++
23 links | 12 authors | 8 languages

Videos

These are a few popular YouTube videos for this problem:
1 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

4 medium 3 hard
8 solutions   August 10, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality