Problem 1392

Abstract / Summary

Find the longest starting part of a string that is also found as a prefix elsewhere in the string.

Note

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

C++ 1392.cpp

class Solution {
    typedef uint8_t hashsize;
    hashsize hash(array<uint32_t, 26>& f)
    {
        hashsize result = 0;
        for (auto x : f)
            result = hashsize(result * 7) ^ x;
        return result;
    }

public:
    string longestPrefix(string s) {
        vector<hashsize> fingerprints(s.size());

        array<uint32_t, 26> current = { 0 };
        for (int i = s.size() - 1; i >= 0; i--)
        {
            current[s[i] - 'a']++;
            fingerprints[i] = hash(current);
        }

        for (int length = s.size() - 1; length > 0; length--)
        {
            current[s[length] - 'a']--;

            int start = s.size() - length;
            if (hash(current) != fingerprints[start])
                continue;

            bool ok = true;
            for (int i = 0; i < length; i++)
                if (s[i] != s[i + start])
                {
                    ok = false;
                    break;
                }

            if (ok)
                return s.substr(0, length);
        }

        return "";
    }
};
44 lines | 1110 bytes | submitted August 10, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (200k+ submissions).

Typical patterns to solve this problem:
  • Hash Function
  • Rolling Hash
  • String
  • String Matching
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 presented Solution class implements a method longestPrefix that receives a lowercase alphabetic string s and returns the longest non-empty prefix which also appears as a contiguous substring elsewhere in s. If no such prefix exists, the method returns an empty string. The algorithm builds a rolling fingerprint of character frequencies from the end of the string toward the front, stores these fingerprints, and then scans possible prefix lengths in decreasing order, comparing fingerprints and finally confirming character-by-character equality.

Core Data Structures

The code defines a type alias hashsize as an 8-bit unsigned integer, which is used for the fingerprint values. A vector fingerprints of this type, sized to the length of s, holds the pre-computed hash for each suffix starting at a given index. An array<uint32_t, 26> named current tracks the frequency of each letter in the current suffix.

Fingerprint Computation

The private helper hash receives a reference to the frequency array and produces a compact 8-bit value. The function iterates over the 26 counters, repeatedly multiplying the intermediate result by 7 and XOR-ing with the current counter. The multiplication and XOR operations are performed in the hashsize domain, causing overflow to wrap around naturally, which yields a deterministic but highly condensed representation of the multiset of characters.

hashsize hash(array<uint32_t, 26>& f)
{
    hashsize result = 0;
    for (auto x : f)
        result = hashsize(result * 7) ^ x;
    return result;
}

Building Suffix Fingerprints

The algorithm first populates fingerprints by walking the input string from right to left. For each position i, it increments the count of the character s[i] in current and stores the hash of the updated frequency array at fingerprints[i]. After this loop, fingerprints[i] represents the fingerprint of the suffix s[i … end].

array<uint32_t, 26> current = { 0 };
for (int i = s.size() - 1; i >= 0; i--)
{
    current[s[i] - 'a']++;
    fingerprints[i] = hash(current);
}

Scanning Candidate Prefix Lengths

The second phase examines possible prefix lengths in descending order, starting from s.size() - 1 down to 1. For each candidate length, the algorithm decrements the frequency of the character that would be excluded from the suffix representation (s[length]). It then computes the start index of the potential matching suffix as s.size() - length. If the fingerprint of the trimmed suffix (hash(current)) does not match the stored fingerprint at the start index, the candidate is rejected immediately, avoiding a costly character comparison.

for (int length = s.size() - 1; length > 0; length--)
{
    current[s[length] - 'a']--;

    int start = s.size() - length;
    if (hash(current) != fingerprints[start])
        continue;
    // ...
}

Verifying Exact Equality

When the fingerprints coincide, the algorithm proceeds to a direct character-by-character check. It iterates over the range [0, length) and compares s[i] with s[i + start]. If any mismatch is found, the candidate is discarded; otherwise, the matching prefix is returned via substr.

bool ok = true;
for (int i = 0; i < length; i++)
    if (s[i] != s[i + start])
    {
        ok = false;
        break;
    }

if (ok)
    return s.substr(0, length);

Edge Cases Handled

The implementation gracefully handles an empty input string: the initial vector allocation yields size zero, the first loop does not execute, and the second loop’s condition length > 0 fails, leading to the final return of an empty string.

When the input consists of a single character, the outer loop again never runs because s.size() - 1 equals zero, and the method returns an empty string, correctly indicating that no non-empty prefix can repeat elsewhere.

If the entire string repeats itself (for example, "aaaa"), the algorithm will eventually consider the full length minus one, find matching fingerprints, and confirm equality, returning the longest proper prefix that appears again.

The fingerprint calculation uses 8-bit overflow, which means that even when the frequency counters become large (as in very long strings with many repeated characters), the hash remains bounded, preventing integer overflow in the fingerprint storage.

Performance Optimizations

The most notable optimization is the use of a compact fingerprint to prune the search space before performing an explicit character comparison. By storing a hash for each suffix and updating the frequency array incrementally, the algorithm avoids recomputing the full frequency distribution for every candidate length. The subtraction of a single character count (current[s[length] - 'a']--) updates the fingerprint in constant time, enabling the outer loop to run in linear time with respect to the number of candidate lengths.

The early continue when fingerprints differ eliminates the inner character-by-character loop for the majority of lengths, especially in strings with diverse character distributions where hash collisions are rare.

Storing fingerprints in a vector of 8-bit values reduces memory pressure compared to larger hash types, allowing the algorithm to scale to longer inputs while keeping cache usage efficient.

The final substr call is executed only once, after a successful match, avoiding unnecessary string copying during the search.

Overall, the combination of incremental frequency tracking, lightweight hashing, and early rejection yields a solution that processes the input with a small constant factor overhead beyond the essential linear passes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train made of colored blocks, where each color represents a different letter. The goal is to look at the front of the train and see if that same pattern of blocks is hiding at the very back of the train too.

To do this quickly, the code starts by looking at the back of the train. It keeps a secret tally of how many blocks of each color are in every possible suffix, which is just a fancy word for the bits at the end. It uses a special trick called a hash, which acts like a tiny signature for a collection of blocks. By turning the pile of colors into one small number, the code can compare chunks of the train very fast without checking every single color one by one.

After making a list of these signatures for all the parts at the end, the code starts from the front of the train and begins stretching its reach. It looks at the front part and checks if its signature matches the one it already calculated for the back. If the signatures match, it means the colors might be the same. To be extra sure, it then looks at each block in order to make sure they actually match, just like double-checking a puzzle piece placement. If they all match perfectly, that part of the train is the winner.

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 = 6 | μ = 5.48 | σ = 1.66

Complexity Analysis

not analyzed yet

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
wisdompeak C++
25 links | 13 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

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