Find palindrome-forming string pairs
Company: Airbnb
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates string-processing and algorithmic design skills, including knowledge of efficient lookup data structures, palindrome properties, handling of edge cases, and time/space complexity analysis.
Constraints
- 0 <= len(words) <= 100000
- All words are distinct and contain only lowercase English letters
- 0 <= len(words[i])
- The sum of all string lengths is at most 200000
Examples
Input: (["bat", "tab", "cat"],)
Expected Output: [[0, 1], [1, 0]]
Explanation: "bat" + "tab" and "tab" + "bat" are palindromes; no pair involving "cat" works.
Input: (["abcd", "dcba", "lls", "s", "sssll"],)
Expected Output: [[0, 1], [1, 0], [2, 4], [3, 2]]
Explanation: The reverse-word pairs are [0,1] and [1,0]. Also, "lls" + "sssll" = "llssssll" and "s" + "lls" = "slls", both palindromes.
Input: (["", "aba", "xyz", "a"],)
Expected Output: [[0, 1], [0, 3], [1, 0], [3, 0]]
Explanation: The empty string can pair on either side with any palindrome, so it matches "aba" and "a".
Input: (["a", "ba", "ab", ""],)
Expected Output: [[0, 1], [0, 3], [1, 2], [2, 0], [2, 1], [3, 0]]
Explanation: "a" + "ba" = "aba", "ba" + "ab" = "baab", "ab" + "a" = "aba", "ab" + "ba" = "abba", and the empty string pairs with the palindrome "a".
Input: ([],)
Expected Output: []
Explanation: With no words, there are no pairs.
Input: (["abc", "def"],)
Expected Output: []
Explanation: Neither concatenation forms a palindrome, so the answer is empty.
Hints
- Comparing every pair is too slow. Try indexing reversed words so that matching candidates can be found while scanning a word character by character.
- A trie of reversed words works well if each node also remembers which words have a palindromic remaining prefix. Precompute palindromic prefixes and suffixes in linear time per word.