00:00

Problem Statement

Input/Output Examples

Visual Explanation

A prefix of s is a palindrome exactly when it equals a suffix of reverse(s). The LPS value at the end of the combined string finds the longest such match, and the # stops matches from crossing between the two halves.

Approaches

Both approaches find the longest palindromic prefix. KMP does it in linear time; the brute force tests prefixes from longest to shortest.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. The KMP approach is linear; the brute force may check n prefixes of up to n characters.

Interview Tips and Recommended Approach

  • Explain the separator. Without #, a border could span both halves and give a length longer than s.
  • Reduce it to a known problem. "Longest palindromic prefix" is the real question.
  • Only add at the front. Adding at the end is a different problem with a mirrored solution.
  • Know the alternatives. Rolling hashes or Manacher's algorithm also find the prefix in linear time.

Recommended Approach: KMP on s + # + reverse(s)

Why: it turns the problem into one LPS computation, giving guaranteed linear time with code you may already know from KMP search.