Palindrome Pairs

HardStringstrie

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a list words of distinct strings (some may be empty). A pair of indices [i, j] with i != j is a palindrome pair if the concatenation words[i] + words[j] reads the same forwards and backwards. Return every palindrome pair as a list of [i, j] pairs. Note that [i, j] and [j, i] are different pairs and each counts only if its own concatenation is a palindrome. The pairs may be returned in any order, but each pair must appear exactly once. Aim for better than checking all O(n^2) concatenations, e.g. O(total length * max word length) using a hash map or trie.

Examples

Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
The palindromes formed are "abcddcba", "dcbaabcd", "slls", and "llssssll".
Input: words = ["bat","tab","cat"]
Output: [[0,1],[1,0]]
"battab" and "tabbat" are palindromes; nothing with "cat" works.
Input: words = ["a",""]
Output: [[0,1],[1,0]]
Both "a" + "" and "" + "a" equal "a".

Constraints

  • 1 <= words.length <= 5000
  • 0 <= words[i].length <= 300
  • `words[i]` consists of lowercase English letters
  • All strings in `words` are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More trie problems