Longest Palindrome by Concatenating Two Letter Words

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.

Example 1
Inputwords = ["lc","cl","gg"]
Output6
One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Example 2
Inputwords = ["ab","ty","yt","lc","cl","ab"]
Output8
One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.

Constraints

  • 1 <= words.length <= 10^5
  • words[i].length == 2
  • words[i] consists of lowercase English letters.

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate