Longest Palindrome by Concatenating Two Letter Words

MediumArrayString

Description

Given an array of strings words where each string is 2 letters, return the longest palindrome that can be formed by concatenating words.

Examples

Input:words = ["lc","cl","gg"]
Output:6
Explanation:

Pair 'lc' with its reverse 'cl' on the ends. Place palindrome 'gg' in middle. Total: 'lc'+'gg'+'cl' = 6 chars.

Input:words = ["ab","ty","gy","fg","lc"]
Output:0
Explanation:

No word has a reverse in the list (e.g., 'ba' for 'ab'), and none are palindromes themselves. No valid concatenation exists.

Input:words = ["aa","bb","cc","dd"]
Output:2
Explanation:

All words are palindromes themselves. It is possible to use all of them: aa + bb + cc + dd = 8. When building a palindrome from pairs, identical letter words can all be placed in the middle.

Constraints

  • 1 ≤ words.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!