AlgoInsight

DSA problem

Palindrome Pairs

HardTriesPattern: Triestop600AirbnbGoogleAmazonMicrosoftMeta

Given a 0-indexed array of unique strings words, return an array of all the palindrome pairs of distinct indices [i, j] such that words[i] + words[j] is a palindrome.

The brute-force solution checks every ordered pair (i, j) with i != j and tests whether words[i] + words[j] is a palindrome. With N words of length up to L, that costs O(N^2 * L) — far too slow when N is in the tens of thousands.

The optimal approach uses a hash map from each word to its index. The key insight is to enumerate splits: for every word w and every split position k, consider prefix = w[:k] and suffix = w[k:]. If prefix is a palindrome AND the reverse of suffix exists in the map at index j != i, then concatenating words[j] in front of w produces a palindrome — i.e. (j, i) is a valid pair. Symmetrically, if suffix is a palindrome AND the reverse of prefix exists at index j != i, then (i, j) is a valid pair.

This split-and-check strategy needs careful handling of duplicate work at the empty-prefix split to avoid emitting each pair twice. The final complexity is O(N * L^2) time and O(N * L) space, which scales well even on the largest inputs in the problem range.

Examples

Example 1
Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: "abcd" + "dcba" = "abcddcba" is a palindrome, giving [0,1]. "dcba" + "abcd" = "dcbaabcd" is a palindrome, giving [1,0]. "s" + "lls" = "slls" is a palindrome, giving [3,2]. "lls" + "sssll" = "llssssll" is a palindrome, giving [2,4].
Example 2
Input: words = ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: "bat" + "tab" = "battab" is a palindrome, giving [0,1]. "tab" + "bat" = "tabbat" is a palindrome, giving [1,0].
Example 3
Input: words = ["a",""]
Output: [[0,1],[1,0]]
Explanation: The empty string concatenated with any palindrome (or vice versa) is itself a palindrome, so both [0,1] and [1,0] are valid since "a" is a palindrome.

Constraints

4 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

triehash-tablestringtwo-pointers

Browse all DSA problems