937. Mirror Word Pairs
A puzzle club glues pairs of tiles together hoping the result reads the same forwards and backwards. Given the list words, find every ordered pair of different indices [i, j] such that words[i] + words[j] (the first word followed by the second) is a palindrome.
Words may be empty and may repeat; equal words stored at different indices count as different tiles. Return the pairs as arrays, sorted ascending by i and then by j, each pair listed once. If no pair works, return an empty list. Testing all pairs takes quadratic time in the number of words; aim for about O(n * L^2) instead, where L is the longest word.
Example 1
- Input:
- words = ["lemon","nomel","x","xx"]
- Output:
- [[0,1],[1,0],[2,3],[3,2]]
- Explanation:
lemon+nomelandnomel+lemonare palindromes, and so arex+xxandxx+x.
Example 2
- Input:
- words = ["","kayak","ab"]
- Output:
- [[0,1],[1,0]]
- Explanation:
The empty word glued before or after the palindrome
kayakkeeps it a palindrome;abpairs with nothing.
Example 3
- Input:
- words = ["ox","xo","ox"]
- Output:
- [[0,1],[1,0],[1,2],[2,1]]
- Explanation:
Equal words at different indices are different words: index 0 and 1 mirror each other, and so do indices 2 and 1.
Constraints
1 ≤ words.length ≤ 5000
0 ≤ words[i].length ≤ 300 and the number of valid pairs is at most 2 * 105
Words consist of lowercase English letters.
How this problem is judged
- Answers
- The outer list may be in any order. Everything inside each item must match exactly.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n * L^2)
- Space
- O(n * L)