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.

30:00

Longest Palindrome by Concatenating Two Letter Words
medium
Free written solution
Topics
Companies

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:
Input: {"words":["lc","cl","gg"]}
Output: 6
Constraints:
  • 1≤words.length≤1051 \leq \text{words.length} \leq 10^5

  • words[i].length==2\text{words}[i].\text{length} == 2

  • words[i] consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["lc","cl","gg"]}

3 two-letter words. A word can sit on the left only if its reverse sits in the mirrored spot on the right, so we match each word with a waiting reverse.

words

lc

0

cl

1

gg

2

waiting for a reverse (count)

empty

pink border: doubled word, can be the center

palindrome, built outward

length = 0

nothing yet

0 mirrored pairs x 4 letters

Variables
VariableValue
length0
DepthFunction Call
Stack empty
0/8