Longest Happy Prefix

HardStringskmp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A **happy prefix** of a string is a non-empty prefix that is also a suffix of the string, **excluding the whole string itself**. Prefix and suffix may overlap. Given s, return its **longest** happy prefix, or the empty string "" if none exists. Comparing every candidate length directly is O(n^2); aim for O(n).

Examples

Input: s = "abcab"
Output: "ab"
`ab` is both a prefix and a suffix; `abc`/`cab` and longer candidates do not match.
Input: s = "aaaa"
Output: "aaa"
The prefix `aaa` (indices 0-2) equals the suffix `aaa` (indices 1-3); overlap is allowed.
Input: s = "abc"
Output: ""
No proper prefix equals a suffix.

Constraints

  • `1 <= s.length <= 10^5`
  • `s` consists of lowercase English letters

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More kmp problems