Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Longest Happy Prefix

XPChallenge Points: 30
levelLevel: Hard

A happy prefix is defined as a non-empty substring that appears both at the beginning and at the end of a string, but it cannot be the entire string itself.

Given a string s, your task is to return the longest such prefix that also occurs as a suffix.
If no prefix matches a suffix, return an empty string.

Example 1:

Input: s = "abcdabc"

Output: "abc"

Explanation:

The prefixes are "a", "ab", "abc", ..." and the suffixes include "abc". The longest prefix appearing as a suffix is "abc".

Example 2:

Input: s = "aaaaa"

Output: "aaaa"

Explanation:

Since all characters are the same, every smaller prefix is also a suffix. The longest valid one is "aaaa".

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result