Given an array of unique strings words, return all pairs of distinct indices (i, j) such that the concatenation words[i] + words[j] is a palindrome.
Function Signature
def palindrome_pairs(words: list[str]) -> list[list[int]]:
Rules
-
Each pair is returned as a two-element list
[i, j]
with
i != j
.
-
Order inside a pair matters:
[i, j]
and
[j, i]
are different pairs, and each one is included only when its own concatenation is a palindrome.
-
The empty string is a palindrome, and
words
may contain it.
-
Return the pairs sorted ascending by
i
, then by
j
. Return an empty list when no pair works.
Constraints
-
1 <= len(words) <= 5000
-
0 <= len(words[i]) <= 300
-
words[i]
consists of lowercase English letters.
-
All strings in
words
are unique.
Examples
Input: words = ["race", "car", "abc", "cba"]
Output: [[0, 1], [2, 3], [3, 2]]
"race" + "car" is "racecar", and both "abccba" and "cbaabc" are palindromes. The reverse order "carrace" is not, so [1, 0] is left out.
Input: words = ["lls", "s", "sssll"]
Output: [[0, 2], [1, 0]]
"lls" + "sssll" is "llssssll" and "s" + "lls" is "slls". No other ordered pair gives a palindrome.
Input: words = ["aba", "", "ab"]
Output: [[0, 1], [1, 0], [2, 0]]
The empty string pairs with the palindrome "aba" in both orders, and "ab" + "aba" is "ababa". The pair [0, 2] gives "abaab", which is not a palindrome.