Ordered Index Pairs Whose Concatenation Reads the Same Backwards
StringsModel answerLast 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
- The algorithm and the data structures you rely on (for example a trie of reversed words, hash maps, or precomputed palindromic prefix/suffix information).
- How you handle the empty string and one-letter words.
- How you guarantee that no pair is produced twice and that
i == jnever appears. - Time and space complexity, including a remark on the worst-case output size.
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core observation
Take an ordered pair of words a = words[i] and b = words[j] where a + b is a palindrome. Compare lengths.
|a| > |b|. Readinga + bbackwards must give the same string, so the first|b|characters ofaarereverse(b). The rest ofasits in the middle and must be a palindrome (and is non-empty).|a| <= |b|. Symmetrically, the last|a|characters ofbarereverse(a). The front part ofbthat remains must be a palindrome (possibly empty).
So each pair is "a reversed word, plus a palindromic piece on one side". The two cases are disjoint, because they split on whether |a| > |b|. That disjointness is what prevents duplicates.
Data structure
Build a trie from the reversed words. Each node stores:
end_word: the index of the word whose reversal ends at this node, or-1.pal_rest: indices of words whose reversal passes through this node and whose not yet consumed part is a palindrome. A word whose reversal ends exactly here has an empty rest, which counts as a palindrome, so it is included.
For a word u of length L, the unconsumed part after d characters of reverse(u) is reverse(u)[d:]. It is a palindrome iff u[:L-d] is. So I only need pre[k], meaning whether u[:k] is a palindrome, for every k.
Palindrome flags in linear time
For a string s, build t = s + '#' + reverse(s) and compute the KMP prefix function. A border of t of length k means s[:k] == reverse(s)[-k:], which is exactly s[:k] being a palindrome. Start from the last value of the prefix function and follow the fallback chain, marking each length. Manacher's algorithm works equally well.
For a query word w, "is w[k:] a palindrome" equals "is reverse(w)[:L-k] a palindrome". So the same routine applied to reverse(w) supplies the tail flags.
Query
For word w at index i, walk down the trie following w's characters from the root.
- Before consuming
w[k](sok < |w|): if the current node hasend_word = j, andw[k:]is a palindrome, report(i, j). This is the|w| > |u|case. - If the walk falls off the trie, stop, since nothing more can match.
- If all of
wis consumed, report(i, j)for everyjin the final node'spal_restwithj != i. This is the|w| <= |u|case, and it includes the equal-length case whereuis exactlyreverse(w).
Step 1 never fires at depth |w|, so an equal-length match is reported only through step 3.
Why there are no duplicates or self-pairs
- The two cases are separated by length, and equal lengths belong only to step 3.
- Each word appears at most once per node's
pal_rest, and words are distinct, so each node has at most oneend_word. - The only way a word can match itself is via
pal_restwhenwis a palindrome, and the filterj != iremoves that.
Edge cases
- Empty string at index
e. Querying with""ends at the root immediately. The root'spal_restcontains every palindromic word (their whole reversal is a palindromic rest) pluseitself, which is filtered. That yields("", p)for every palindromicp. Querying with a palindromicpat depth 0 findsend_word = eat the root withp[0:]a palindrome, which yields(p, ""). Each order is emitted exactly once. - One-letter words. They are palindromes, so they pair with
""in both orders. They cannot pair with themselves, since words are distinct."a"and"ba"give"aba"through step 3. - Huge output.
["a","aa","aaa",...]makes nearly every ordered pair valid, so the output can be quadratic and no algorithm can avoid that.
Complexity
Let S be the total character count, n the number of words and P the number of reported pairs.
- Palindrome flags: O(S) overall.
- Trie construction: O(S), with at most
S + 1nodes. - Queries: each walks at most
|w|nodes, and the scan ofpal_restat the end costs O(size), which is bounded by the pairs emitted plus at most one filtered entry. Total O(S + n + P) time. - Space: O(S + n + P) for the trie and the
pal_restlists (each word is in at mostL + 1lists) plus the output.
Comparison with the common alternative
The popular hash-map solution stores each word, and for every word tries each of its L + 1 split points. It checks whether one half is a palindrome and the reverse of the other half is in the map. This costs O(Σ L²) because of slicing and palindrome checks. With one 200,000-character word that is around 4·10^10 operations. The trie with precomputed flags removes the quadratic factor.
Code
from typing import List
def pal_prefix_flags(s: str) -> List[bool]:
"""flags[k] is True iff s[:k] is a palindrome (k = 0..len(s))."""
n = len(s)
flags = [False] * (n + 1)
flags[0] = True
if n == 0:
return flags
t = s + "#" + s[::-1]
pi = [0] * len(t)
for x in range(1, len(t)):
k = pi[x - 1]
while k and t[x] != t[k]:
k = pi[k - 1]
if t[x] == t[k]:
k += 1
pi[x] = k
k = pi[-1]
while k > 0:
flags[k] = True
k = pi[k - 1]
return flags
def palindrome_pairs(words: List[str]) -> List[List[int]]:
nxt = [{}] # children of each trie node
end_word = [-1] # word whose reversal ends here
pal_rest = [[]] # words passing here with palindromic remainder
for j, u in enumerate(words):
pre = pal_prefix_flags(u)
L = len(u)
node = 0
for d in range(L):
if pre[L - d]: # reverse(u)[d:] is a palindrome
pal_rest[node].append(j)
c = u[L - 1 - d]
child = nxt[node].get(c)
if child is None:
child = len(nxt)
nxt[node][c] = child
nxt.append({})
end_word.append(-1)
pal_rest.append([])
node = child
end_word[node] = j
pal_rest[node].append(j) # empty remainder
res = []
for i, w in enumerate(words):
L = len(w)
tail = pal_prefix_flags(w[::-1]) # tail[m]: w[L-m:] is a palindrome
node = 0
completed = True
for k in range(L):
e = end_word[node]
if e != -1 and tail[L - k]: # w[k:] is a palindrome
res.append([i, e])
node = nxt[node].get(w[k], -1)
if node == -1:
completed = False
break
if completed:
for j in pal_rest[node]:
if j != i:
res.append([i, j])
return res
Test cases worth running
["abcd","dcba","lls","s","sssll"]gives[[0,1],[1,0],[3,2],[2,4]]in any order.["bat","tab","cat"]gives[[0,1],[1,0]].["a",""]gives[[0,1],[1,0]].["a","ba"]gives[[0,1]]only, because"baa"is not a palindrome.["abc","def"]gives[].["a","aa","aaa"]gives all six ordered pairs.- A single very long word, to confirm the run time stays linear.
Common mistakes
- Reporting the exact-reverse pair twice, once from each case.
- Forgetting that a palindromic word pairs with
""in both orders. - Allowing
(i, i)for palindromic words. - Checking palindromes by slicing at every split, which silently reintroduces quadratic cost.