Longest Palindrome by Concatenating Two Letter Words (LeetCode 2131): Solution and Explanation
Each word has two letters. Pick some words and order them to form the longest palindrome, using each word at most once, and return its length.
Intuition
In a palindrome built from two-letter blocks, the block k places from the left must be the reverse of the block k places from the right. So blocks come in mirrored pairs (w, reverse(w)), each worth 4 letters.
The only block that does not need a partner is the one in the exact middle, and it must read the same both ways, which means its two letters are equal, like "gg". At most one such block fits.
Pairing greedily is safe: when a word arrives and its reverse is waiting, matching them now never hurts, because any word can pair only with its own reverse.
A doubled word such as "aa" is its own reverse, so two copies pair with each other. An odd copy left over is the center candidate.
Approach: Greedy pairing with a count map
- Keep
count, the number of unmatched copies of each word, andlength = 0. - For each word
w, letrevbe its reverse. Ifcount[rev] > 0, decrement it and add 4 tolength. Otherwise incrementcount[w]. - After the loop, if any doubled word still has a positive count, add 2 for the center.
- Return
length.
Step-by-step example
words = ["lc","cl","gg"]
- "lc": its reverse "cl" is not waiting, so "lc" waits.
- "cl": its reverse "lc" is waiting. Pair them as "lc ... cl", length = 4.
- "gg": its reverse is "gg", not waiting, so "gg" waits.
- After the loop, "gg" is unmatched and doubled, so it goes in the center: "lc gg cl", length = 6.
Code: Python, Java, C++
1class Solution:
2 def longestPalindrome(self, words: List[str]) -> int:
3 count = {}
4 length = 0
5 for w in words:
6 rev = w[::-1]
7 if count.get(rev, 0) > 0:
8 count[rev] -= 1
9 length += 4
10 else:
11 count[w] = count.get(w, 0) + 1
12 for w, c in count.items():
13 if c > 0 and w[0] == w[1]:
14 return length + 2
15 return length1class Solution {
2 public int longestPalindrome(String[] words) {
3 int[][] count = new int[26][26];
4 int length = 0;
5 for (String w : words) {
6 int a = w.charAt(0) - 'a', b = w.charAt(1) - 'a';
7 if (count[b][a] > 0) {
8 count[b][a]--;
9 length += 4;
10 } else {
11 count[a][b]++;
12 }
13 }
14 for (int a = 0; a < 26; a++) {
15 if (count[a][a] > 0) {
16 return length + 2;
17 }
18 }
19 return length;
20 }
21}1class Solution {
2public:
3 int longestPalindrome(vector<string>& words) {
4 int count[26][26] = {};
5 int length = 0;
6 for (const string& w : words) {
7 int a = w[0] - 'a', b = w[1] - 'a';
8 if (count[b][a] > 0) {
9 count[b][a]--;
10 length += 4;
11 } else {
12 count[a][b]++;
13 }
14 }
15 for (int a = 0; a < 26; a++) {
16 if (count[a][a] > 0) {
17 return length + 2;
18 }
19 }
20 return length;
21 }
22};Time and space complexity
O(n)
Each word costs one map lookup and one update, then the leftover scan is over at most 26 * 26 keys.
O(1)
There are only 26 * 26 distinct two-letter words, so the count table has a fixed size.
Other approaches
Count first, then pair by formula (time O(n), space O(1))
Count every word. For a word with different letters, add 4 * min(count[w], count[rev]) once per unordered pair. For a doubled word, add 4 * (count // 2) and remember whether any doubled word has an odd count for the center.
Fixed 26 x 26 table (time O(n), space O(1))
The same greedy pairing, but with a 2D integer array indexed by the two letters instead of a hash map. This is what the Java, C++, C# and Go versions use.
Common mistakes
- Adding a center for every leftover doubled word. Only one block can sit in the middle.
- Treating "aa" as unpairable. Two copies of a doubled word form a mirrored pair worth 4.
- Adding 2 for a leftover word with different letters such as "ab". It is not a palindrome by itself.
- Counting a pair twice, once when each of the two words is visited.
Frequently asked questions
Why is greedy matching correct?
A word can only ever be mirrored by its own reverse. Matching an arriving word with a waiting reverse uses two copies that could not be used in any other pair, so it never blocks a better choice.
Why can only one word go in the middle?
The center of an even-length palindrome made of two-letter blocks is a single block position. Any other block has a mirrored partner position on the other side.
What if three copies of "aa" appear?
Two of them pair for 4 letters and the third can be the center for 2 more, giving 6 from that word alone.