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…

--

--