#1392

Longest Happy Prefix

Hard LPS array

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A "happy prefix" is a non-empty prefix that is also a suffix, but not the whole string. Return the longest one, or "".

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest prefix that is also a suffix (not the whole string).

Why this works: that is exactly the last value of the LPS array.

Example: "level"

lps = [0, 0, 0, 0, 1] → "l"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Comparing every prefix with every suffix — O(n²) and too slow for n = 10^5.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon