937. Mirror Word Pairs

Hard7.5 points estimatedTrieStringHash Table4 hints

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+nomel and nomel+lemon are palindromes, and so are x+xx and xx+x.

Example 2

Input:
words = ["","kayak","ab"]
Output:
[[0,1],[1,0]]
Explanation:

The empty word glued before or after the palindrome kayak keeps it a palindrome; ab pairs 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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…