Java String Program · S69
Palindrome Pairs in Java
Which pairs of words read the same backwards when joined? Instead of trying every pair, split each word into a palindrome part and a remainder, and look up the remainder's reverse.
Problem Statement
Given a list of distinct words, return every ordered pair of indexes [i, j], with i ≠ j, such that words[i] + words[j] is a palindrome.
Return the pairs sorted by i, then by j. The empty string may be one of the words.
Input/Output Examples
["abc", "cba", "ab", "b"]Output[[0, 1], [1, 0], [2, 1], [3, 2]]Explanation: abccba, cbaabc, abcba and bab.["java", "avaj", "x"]Output[[0, 1], [1, 0]]Explanation: javaavaj and avajjava; x does not pair with either.["a", ""]Output[[0, 1], [1, 0]]Explanation: joining a palindrome with "" leaves a palindrome.Visual Explanation
- Word "cba"splits|cbac|bacb|acba|try every split
- Split c|bapartscbaprefix "c" is a palindrome
- Look upreverseabreverse("ba") = "ab" "ab" is word 2
- Pairresultab + cba"abcba" is a palindrome
- Done[2, 1]
If the prefix is a palindrome, then reverse(suffix) + word is a palindrome; if the suffix is a palindrome, then word + reverse(prefix) is one. A hash map turns each check into a single lookup.
Approaches
The map-based approach checks each word's splits. The brute force checks every ordered pair of words.
Approach 1: HashMap of Words (Recommended)
Idea: store every word's index in a map; for each split of each word, look up the reverse of the non-palindromic part.
- Map each word to its index.
- For every split
prefix | suffixof wordi: - If
prefixis a palindrome andreverse(suffix)is wordj ≠ i, add[j, i]. - If
suffixis a non-empty palindrome andreverse(prefix)is wordj ≠ i, add[i, j].
Time: O(n × k²) · Space: O(n × k). n words of length up to k.
Approach 2: Check Every Pair
Idea: concatenate every ordered pair of different words and test whether the result is a palindrome.
- Loop over every
iand everyj ≠ i. - Test whether
words[i] + words[j]is a palindrome. - Record
[i, j]if it is.
Time: O(n² × k) · Space: O(k).
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: HashMap of Words (Recommended)
The cut < w.length() check on the second rule avoids reporting the same pair twice when both parts are empty or whole.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalPairsMap {
// Split each word into prefix + suffix; if one part is a palindrome, look up the reverse of the other
static List<List<Integer>> palindromePairs(String[] words) {
Map<String, Integer> index = new HashMap<>();
for (int i = 0; i < words.length; i++) {
index.put(words[i], i);
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
String w = words[i];
for (int cut = 0; cut <= w.length(); cut++) {
String prefix = w.substring(0, cut);
String suffix = w.substring(cut);
if (isPalindrome(prefix)) { // other + w, where other = reverse(suffix)
Integer j = index.get(new StringBuilder(suffix).reverse().toString());
if (j != null && j != i) {
result.add(List.of(j, i));
}
}
if (cut < w.length() && isPalindrome(suffix)) { // w + other, where other = reverse(prefix)
Integer j = index.get(new StringBuilder(prefix).reverse().toString());
if (j != null && j != i) {
result.add(List.of(i, j));
}
}
}
}
result.sort((a, b) -> a.get(0) != b.get(0) ? a.get(0) - b.get(0) : a.get(1) - b.get(1));
return result;
}
private static boolean isPalindrome(String s) {
for (int l = 0, r = s.length() - 1; l < r; l++, r--) {
if (s.charAt(l) != s.charAt(r)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[][] inputs = {{"abc", "cba", "ab", "b"}, {"java", "avaj", "x"}, {"a", ""}};
for (String[] words : inputs) {
System.out.println(java.util.Arrays.toString(words) + " -> " + palindromePairs(words));
}
}
}
[abc, cba, ab, b] -> [[0, 1], [1, 0], [2, 1], [3, 2]] [java, avaj, x] -> [[0, 1], [1, 0]] [a, ] -> [[0, 1], [1, 0]]
Time complexity: O(n × k²) · Space complexity: O(n × k).
Approach 2: Check Every Pair
Simple and obviously correct; it is the reference the fast version is tested against.
import java.util.ArrayList;
import java.util.List;
public class PalPairsBrute {
// Checks every ordered pair: O(n^2 * k)
static List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words.length; j++) {
if (i != j && isPalindrome(words[i] + words[j])) {
result.add(List.of(i, j));
}
}
}
return result;
}
private static boolean isPalindrome(String s) {
for (int l = 0, r = s.length() - 1; l < r; l++, r--) {
if (s.charAt(l) != s.charAt(r)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[][] inputs = {{"abc", "cba", "ab", "b"}, {"java", "avaj", "x"}, {"a", ""}};
for (String[] words : inputs) {
System.out.println(java.util.Arrays.toString(words) + " -> " + palindromePairs(words));
}
}
}
[abc, cba, ab, b] -> [[0, 1], [1, 0], [2, 1], [3, 2]] [java, avaj, x] -> [[0, 1], [1, 0]] [a, ] -> [[0, 1], [1, 0]]
Time complexity: O(n² × k) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| HashMap of Words | O(n × k²) | O(n × k) |
| Check Every Pair | O(n² × k) | O(k) |
Here n is the number of words and k the maximum word length. The map approach checks k + 1 splits per word with O(k) work each, which beats checking all n² pairs when there are many short words.
Interview Tips and Recommended Approach
- Handle the empty string. It pairs with every palindrome in both orders.
- Avoid duplicate pairs. Make sure a split where both rules apply is not counted twice.
- Explain the two directions. A palindromic prefix gives a partner in front; a palindromic suffix gives a partner behind.
- Mention the trie variant. A trie of reversed words gives the same complexity with different trade-offs.
Recommended Approach: HashMap of Words
Why: it replaces the quadratic pair check with hash lookups per split, which scales much better when the list is long and the words are short.