You get an array words of distinct lowercase strings. A pair of indices [i, j] with i != j is a palindrome pair when words[i] + words[j] reads the same forwards and backwards.
Return every palindrome pair, in any order. The order inside a pair matters: [i, j] and [j, i] are different pairs, and both count when both joins work.
Example 1
Input: words = ["ab", "ba", "b"] Output: [[0, 1], [1, 0], [1, 2], [2, 0]] Why: abba, baab, bab and bab are palindromes
2 more examples and the constraints
Example 2
Input: words = ["dog", "cow", "pig"] Output: [] Why: no join of two of them is a palindrome
Example 3
Input: words = ["", "pop", "xy"] Output: [[0, 1], [1, 0]] Why: the empty word joins any palindrome, on either side
Constraints
- 1 ≤ length of words ≤ 5,000
- 0 ≤ length of words[i] ≤ 300
- words[i] uses only lowercase English letters; all words are distinct
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every pairO(n² · k)
- Split each word, look up the reverseO(n · k²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 5,000 words of 300 letters | Verdict |
|---|---|---|---|
| Try every pair | O(n² · k) | Too slow for 5,000 words | |
| Split each word, look up the reverse | O(n · k²) | Best; linear in the word count |
n = number of words, k = length of the longest word.
Edge cases to test
- The empty word. "" pairs with every palindrome on both sides; it is found through the empty prefix or suffix.
- Exact reverses. ["live", "evil"] gives both [0, 1] and [1, 0], each found once.
- A word that is its own reverse. "pop" finds itself in the map; skip it because
imust differ fromj. - One word. With nothing to pair, the answer is [].
Common mistakes
- Running the suffix check at every cut, which counts exact-reverse pairs twice.
- Forgetting to skip
j == iwhen a word is a palindrome. - Putting the pair in the wrong order: a partner found from the prefix check goes first.
How to talk through it
- 1Clarify. Ordered pairs, words distinct, the empty word allowed? Any output order?
- 2Give the brute force. Every ordered pair, check the join: O(n² · k), too slow for 5,000 words.
- 3Describe a partner. If a prefix is a palindrome, the partner is the reverse of the rest, placed in front.
- 4Use a hash map. Look each needed reverse up in O(1); that gives O(n · k²).
- 5Test out loud. Try the empty word, two exact reverses, and a palindrome word on its own.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?