Longest Palindrome by Concatenating Two Letter Words Problem
#2131
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2131.
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
Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Note that "clgglc" is another longest palindrome that can be created.
Example 2:
Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
Note that "lcyttycl" is another longest palindrome that can be created.
Example 3:
Input: words = ["cc","ll","xx"]
Output: 2
Explanation: One longest palindrome is "cc", of length 2.
Note that "ll" is another longest palindrome that can be created, and so is "xx".
Constraints:
1 <= words.length <= 10^5words[i].length == 2words[i]consists of lowercase English letters.
Solution
Approach: Greedy + Hash Table
Count how many times each word occurs, then look at each distinct word k with count v:
- If both letters of
kare equal (likegg), pairs of it can go at both ends of the palindrome, which adds(v / 2) * 4letters (integer division). Ifvis odd, one copy is left over and can serve as the middle, so remember that in a flag. - Otherwise pair
kwith its reversek[1] + k[0]:min(v, cnt[reverse])pairs fit, each adding 2 letters on this side. The reverse word does the same when it is visited, so each pair is counted from both words and the total is right.
At the end, if any leftover equal-letter word exists, add 2 for the middle.
Time O(n), space O(n), where n is the number of words.
from collections import Counter
class Solution:
def longestPalindrome(self, words: List[str]) -> int:
cnt = Counter(words)
ans = x = 0
for k, v in cnt.items():
if k[0] == k[1]:
x += v & 1
ans += v // 2 * 2 * 2
else:
ans += min(v, cnt[k[::-1]]) * 2
ans += 2 if x else 0
return ans