Java String Program · S67
Shortest Palindrome by Adding Characters in Front in Java
Find the longest prefix that is already a palindrome. Everything after it must be mirrored onto the front, so the shortest result adds exactly those characters in reverse.
Problem Statement
Given a string, add the fewest characters to its front so that the result is a palindrome, and return that palindrome.
A string that is already a palindrome is returned unchanged. The empty string returns the empty string.
Input/Output Examples
"java"Output"avajava"Explanation: only "j" is a palindromic prefix, so "ava" is mirrored in front."aabba"Output"abbaabba"Explanation: "aa" is the longest palindromic prefix; "bba" reversed is "abb"."racecar"Output"racecar"Explanation: nothing needs to be added.Visual Explanation
- Combinetextjava#avajs + "#" + reverse(s)
- LPS endborderjlast LPS value = 1 palindromic prefix "j"
- Addfrontavareverse of the rest "ava"
- Done"avajava"
"java", the LPS value at the end of "java#avaj" is 1, so the longest palindromic prefix is "j". The remaining "ava", reversed, is added in front.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.
Approach 1: KMP on s + # + reverse(s) (Recommended)
Idea: the LPS value at the end of s + "#" + reverse(s) is the length of the longest palindromic prefix.
- Build the combined string with a separator that does not occur in
s. - Compute its LPS array.
- Let
keepbe the last LPS value. - Return the first
n - keepcharacters ofreverse(s)followed bys.
Time: O(n) · Space: O(n).
Approach 2: Check Prefixes From Longest
Idea: test the whole string, then shorter and shorter prefixes, until one is a palindrome.
- Start with
keep = n. - While
s[0..keep)is not a palindrome, decreasekeep. - Add the reverse of
s[keep..]in front.
Time: O(n²) · Space: O(n).
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.
Approach 1: KMP on s + # + reverse(s) (Recommended)
One linear pass over a string of length 2n + 1.
public class ShortestPalKmp {
// The longest palindromic prefix of s = the longest border of s + "#" + reverse(s)
static String shortestPalindrome(String s) {
String rev = new StringBuilder(s).reverse().toString();
String combined = s + "#" + rev;
int[] lps = new int[combined.length()];
for (int i = 1; i < combined.length(); i++) {
int len = lps[i - 1];
while (len > 0 && combined.charAt(i) != combined.charAt(len)) {
len = lps[len - 1];
}
if (combined.charAt(i) == combined.charAt(len)) {
len++;
}
lps[i] = len;
}
int keep = lps[combined.length() - 1]; // length of the palindromic prefix
return rev.substring(0, s.length() - keep) + s;
}
public static void main(String[] args) {
String[] inputs = {"java", "aabba", "racecar", ""};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + shortestPalindrome(s) + "\"");
}
}
}
"java" -> "avajava" "aabba" -> "abbaabba" "racecar" -> "racecar" "" -> ""
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Check Prefixes From Longest
Very clear, and fast when the palindromic prefix is long, but quadratic on inputs such as "aaaa…ab".
public class ShortestPalBrute {
// Tries prefixes from longest to shortest; the first palindrome decides what to add
static String shortestPalindrome(String s) {
int keep = s.length();
while (keep > 0 && !isPalindrome(s, keep)) {
keep--;
}
String rest = s.substring(keep);
return new StringBuilder(rest).reverse() + s;
}
private static boolean isPalindrome(String s, int len) {
for (int l = 0, r = len - 1; l < r; l++, r--) {
if (s.charAt(l) != s.charAt(r)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] inputs = {"java", "aabba", "racecar", ""};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + shortestPalindrome(s) + "\"");
}
}
}
"java" -> "avajava" "aabba" -> "abbaabba" "racecar" -> "racecar" "" -> ""
Time complexity: O(n²) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| KMP on s + # + reverse(s) | O(n) | O(n) |
| Check Prefixes From Longest | O(n²) | O(n) |
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 thans. - 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.