KatInterview

Ordered Index Pairs Whose Concatenation Reads the Same Backwards

StringsModel answer
HardModel answerStringspalindrometriehashing

Last updated

Given distinct lowercase words, list every ordered index pair whose concatenation is a palindrome, doing much better than checking all pairs.

You have a list words of distinct strings made of lowercase letters. The empty string may appear in the list.

Return every ordered pair of indices (i, j) with i != j such that the string words[i] + words[j] is a palindrome. The pairs (i, j) and (j, i) are different and are reported independently, each only if it qualifies. No pair should be reported twice.

Limits

  • Up to 100,000 words.
  • At most 200,000 characters in total across all words.

Checking every pair of words and testing each concatenation is far too slow at these limits. Design something close to linear in the input size plus the output size.

What to cover in your answer

  1. The algorithm and the data structures you rely on (for example a trie of reversed words, hash maps, or precomputed palindromic prefix/suffix information).
  2. How you handle the empty string and one-letter words.
  3. How you guarantee that no pair is produced twice and that i == j never appears.
  4. Time and space complexity, including a remark on the worst-case output size.
  5. A set of test cases, including tricky ones.

Example

words = ["abcd", "dcba", "lls", "s", "sssll"] gives pairs for "abcddcba", "dcbaabcd", "slls" and "llssssll", so the answer is [[0,1],[1,0],[3,2],[2,4]] in any order.

Hints

Hint 1

Split any valid concatenation `a + b` by length. If `a` is longer than `b`, then `a` begins with the reverse of `b` and the remaining tail of `a` is itself a palindrome. If `a` is not longer, then `b` ends with the reverse of `a` and the leftover front part of `b` is a palindrome.

Hint 2

Store the reversed words in a trie, so that walking along `a` character by character tests 'is some word's reverse a prefix of `a`' and 'is `a` a prefix of some reversed word' in one pass. At each node, remember which word ends there, and which words pass through it with a palindromic leftover.

Hint 3

To test 'is this tail/leftover a palindrome' in O(1), precompute for every word which prefix lengths are palindromes (KMP prefix function on `s + '#' + reverse(s)`, or Manacher). Run it on the reversed word to get suffix information. Treat equal-length matches in exactly one of the two cases to avoid duplicates.