Ctrl K

Glued Into a Palindrome

Hard
You are given a list of **distinct** strings words. Find every ordered pair of indices [i, j] with i != j such that gluing words[i] + words[j] gives a string that reads the same forwards and backwards. Order inside a pair matters: [i, j] and [j, i] are different glued strings, and each one is included only if it is itself a palindrome. The pairs themselves may be returned in any order. Checking every pair takes O(n² · L). Aim for a solution whose running time depends on the total length of the words rather than on the number of words squared.
Example 1
words=['ten', 'net', 'noon', 'on'] → [[0, 1], [1, 0]]

"ten" + "net" = "tennet" and "net" + "ten" = "netten" both read the same backwards. "noon" and "on" do not combine into a palindrome in either order, so the answer is [0, 1] and [1, 0].

Example 2
words=['lev', 'el', 'ab', 'xyzba'] → [[0, 1]]

"lev" + "el" = "level" is a palindrome, giving [0, 1]. Neither "abxyzba" nor "xyzbaab" is one, so [[0, 1]] is the whole answer.

Example 3
words=['', 'aba', 'c'] → [[1, 0], [0, 1], [2, 0], [0, 2]]

The empty word can be glued to any palindrome on either side: [0, 1], [1, 0], [0, 2] and [2, 0].

Constraints
  • 1 ≤ len(words) ≤ 5000
  • 0 ≤ len(words[i]) ≤ 300
  • Words consist of lowercase English letters
  • All words are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardWords That Fit Each Puzzle HardPurge Twin Folders HardSplit Into Dictionary Words MediumHighlight Search Hits Medium
loading Python…
Input
words=['ten', 'net', 'noon', 'on']
Expected
[[0, 1], [1, 0]]

Run checks the first 3 tests in your browser. Submit checks all 80 tests on the server, hidden ones included.