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^5
words[i].length == 2
words[i]
consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach for finding the longest palindrome made from word pairs involves trying every possible combination of words. We check each combination to see if it forms a palindrome and keep track of the longest one we find. This involves a lot of checking and re-checking of different arrangements.
Here's how the algorithm would work step-by-step:
def longest_palindrome_brute_force(words):
longest_palindrome_length = 0
number_of_words = len(words)
for start_index in range(number_of_words):
for length in range(2, number_of_words + 1):
for i in range(number_of_words - length + 1):
current_combination = words[i:i+length]
combined_word = "".join(current_combination)
# Check if the combined word is a palindrome
if combined_word == combined_word[::-1]:
# Update the longest palindrome length if needed
longest_palindrome_length = max(longest_palindrome_length, len(combined_word))
return longest_palindrome_length
The key idea is to pair words with their reversed counterparts to form palindromes. We also handle cases where single-letter repeated words can be placed in the center of the palindrome if we have an odd number of them.
Here's how the algorithm would work step-by-step:
def longestPalindrome(words):
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
palindrome_length = 0
central_word_used = False
for word in word_counts:
reversed_word = word[::-1]
if word in word_counts and reversed_word in word_counts:
# Pair words with their reverses to form palindromes
if word != reversed_word:
pairs = min(word_counts[word], word_counts[reversed_word])
palindrome_length += pairs * 4
word_counts[word] -= pairs
word_counts[reversed_word] -= pairs
else:
# Handle same-letter words ('aa', 'bb') carefully
pairs = word_counts[word] // 2
palindrome_length += pairs * 4
word_counts[word] -= pairs * 2
# Check if we can use a single same-letter word in the center
if word_counts[word] == 1:
# Use center word if not yet used.
if not central_word_used:
palindrome_length += 2
central_word_used = True
return palindrome_length
Case | How to Handle |
---|---|
Empty input array | Return 0 since no palindrome can be formed. |
Array with a single two-letter word | If the single word is a palindrome (e.g., 'aa'), store it for possible center; otherwise, return 0. |
Array contains only palindromic two-letter words (e.g., ['aa', 'bb', 'aa']) | Handle by counting pairs and allowing at most one unpaired palindromic word as the center. |
Array contains no palindromes at all | The algorithm should correctly identify that there's no center and still find all reverse pairs. |
Maximum array size with varied words (stress test) | Use efficient data structures (hash maps) to ensure the solution scales reasonably. |
Words longer or shorter than two letters (invalid input) | The problem statement specifies two-letter words; input validation at the beginning can ensure correct input. |
Array contains duplicate pairs | The frequency map will account for multiple pairs and handle them correctly. |
Integer overflow if the length becomes too long | Ensure the data type used to store the length is sufficiently large (e.g., long long in C++ or equivalent in other languages) to avoid overflow issues. |