Leetcode 2131: Longest Palindrome by Concatenating Two Letter Words

Pierre-Marie Poitevin
3 min readJan 9, 2022

In this problem, we want to form the longest possible palindrome by concatenating two letter words from a list:

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.

We are also given a few examples:

Examples and constraints

To solve the problem, we want to match strings with there “reverse”, for instance, match lc with cl. Each time we find such a pair, we are able to add 4 characters to the maximum palindrome.

Also, we are able to use use one “self palindrome”, that is a string with 2 characters that are the same, in the middle of the palindrome, and add 2 characters to the maximum palindrome. For instance in the first example: “lcggcl”.

That’s it, there is no other way to extend the palindrome. We want to solve the problem in linear time with the number of words n as much as possible. to do that, we will keep track of all the words we encountered, or more precisely, we will store their inverse (lc to cl), along with the number of time we encountered it. When we find a matching string, we will decrease the count, as there is one less string to match. We will use a map to keep track of all the words encountered.

We will also keep track of the number of self palindromes we encountered. Each time we find an unmatched self palindrome, we add one to the count. Each time we find a palindrome that can be matched to an existing one, we remove one to the count. If the count is greater than 0 at the end of the loop, we add 2 to the result as we are able to put one of the unmatched self palindrome in the middle of the string.

Jamboard with main solution ideas

In Java, I obtained the following code:

class Solution {
public int…

--

--