Longest Happy Prefix — LeetCode 1392 Python Solution

HardStringString MatchingHash FunctionRolling Hash
Problem
#1392
Pattern
Hash Map
Reading time
2 min

The problem

A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s, return the longest happy prefix of s.

Example

Input
s = "level"
Output
"l"
Explanation
s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".

Python solution

Python
class Solution:
    def longestPrefix(self, s: str) -> str:
        for i in range(1, len(s)):
            if s[:-i] == s[i:]:
                return s[i:]
        return ''

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1392. Longest Happy Prefix is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1392. Longest Happy Prefix?
LeetCode 1392. Longest Happy Prefix is rated Hard on LeetCode.
What is the time complexity of LeetCode 1392. Longest Happy Prefix?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1392. Longest Happy Prefix?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1392. Longest Happy Prefix cover?
LeetCode 1392. Longest Happy Prefix is tagged String, String Matching, Hash Function and Rolling Hash on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview