FastPrepLongest Happy Prefix
Problems/Longest Happy Prefix

Longest Happy Prefix

Amazon logoAmazon● HardFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source provides the exact canonical Longest Happy Prefix problem URL. The judged proper-prefix-equals-suffix contract follows that canonical exercise, with an estimated 99% source match.

A string is a happy prefix of s when it is a non-empty proper prefix of s and is also a suffix of s.

Return the longest happy prefix. If none exists, return the empty string.

Function

longestPrefix(s: String) → String

Examples

Example 1

s = "level"return = "l"

The prefix l is also the suffix, and no longer proper prefix matches.

Example 2

s = "ababab"return = "abab"

The first four characters equal the last four characters.

Example 3

s = "a"return = ""

A one-character string has no non-empty proper prefix.

Constraints

  • 1 <= s.length <= 100000.
  • s contains only lowercase English letters.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public String longestPrefix(String s) {
      // write your code here
    }
}
Checking account…