Longest Palindrome by Concatenating Two-Letter Words

Max-length palindrome built from given 2-letter words — pair each word with its reverse.

Medium
Time O(N) Space O(N)
LeetCode
4 min read
hash-map counting strings

Problem#

Given an array of 2-letter strings words, build the longest palindrome by concatenating some of them. Return its length, or 0 if impossible.

Examples#

  • words = ["lc","cl","gg"]6 ("lcggcl").
  • words = ["ab","ty","yt","lc","cl","ab"]8 ("tylcclyt").
  • words = ["cc","ll","xx"]2.

Constraints#

  • 1 <= words.length <= 10^5, words are length 2, lowercase letters.

Hints#

Hint
For each word xy, pair it with yx. Same-letter words (aa, bb, etc.) can be placed at the palindrome’s center once.

Approach#

Count word frequencies. For each word w = xy: if x != y, pair as many copies of w as we have of its reverse yx — contributes 4 * min(cnt[w], cnt[yx]) to the answer (divide by 2 to avoid double-counting). For x == y, pair up cnt[w] / 2 pairs (contributing 4 * pairs); reserve one same-letter word as the center if any has odd count.

Solution#

Longest Palindrome by Concatenating Two-Letter Words
class Solution {
public:
int longestPalindrome(vector<string>& words) {
unordered_map<string,int> cnt;
for (auto& w : words) ++cnt[w];
int ans = 0;
bool centerAvail = false;
for (auto& [w, c] : cnt) {
string rev = {w[1], w[0]};
if (w == rev) {
ans += (c / 2) * 4;
if (c & 1) centerAvail = true;
} else if (w < rev) { // count each unordered pair once
auto it = cnt.find(rev);
if (it != cnt.end()) ans += min(c, it->second) * 4;
}
}
if (centerAvail) ans += 2;
return ans;
}
};

Editorial#

The w < rev guard prevents counting each (w, rev) pair twice. Same-letter words xx are special: they can pair with another copy of xx (each pair contributes 4 letters), and one leftover odd xx can sit in the palindrome’s center contributing 2 more letters. Only one center is allowed regardless of how many such words have odd counts.

Complexity#

  • Time: O(N).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.