Sitemap
Photo by Chris Ried on Unsplash

LeetCode day320–2131

2 min readMay 25, 2025

--

Everyday has one random leetcode quiz. Today’s quiz is 2131. Longest Palindrome by Concatenating Two Letter Words

Description:

You are given an array of strings words. Each element of words consists of two lowercase English letters.

Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.

Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.

A palindrome is a string that reads the same forward and backward.

Get Jimmy’s stories in your inbox

Join Medium for free to get updates from this writer.

Example 1:

Input: words = ["lc","cl","gg"]
Output: 6
Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Note that "clgglc" is another longest palindrome that can be created.

Example 2:

Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
Note that "lcyttycl" is another longest palindrome that can be created.

Example 2:

Input: words = ["cc","ll","xx"]
Output: 2
Explanation: One longest palindrome is "cc", of length 2.
Note that "ll" is another longest palindrome that can be created, and so is "xx".

Check the entire text and record the number of times each word appears.

If two words are pairable, increase the count by 4 and decrease the appearance count of both words by 1. Otherwise, increase the appearance count of the word by 1.

Then, check the list of pairable words:

  • If any word is a palindrome, return count + 2 as the answer.
  • Otherwise, return count as the answer.

If words length is n, the time complexity is O(n)

/**
* @param {string[]} words
* @return {number}
*/
var longestPalindrome = function (words) {
const pairWords = {}
let count = 0

words.forEach((word) => {
const reversedWord = word[1] + word[0]

if (pairWords[word]) {
pairWords[word]--
count += 4
} else {
pairWords[reversedWord] = (pairWords[reversedWord] ?? 0) + 1
}
})

const hasSameWord = Object.entries(pairWords)
.filter(([word, val]) => val && word === word[1] + word[0])
.length > 0

return hasSameWord ? count + 2 : count
};

--

--

Jimmy
Jimmy

Written by Jimmy

The frontend enginer is learning