#2131
Longest Palindrome by Concatenating Two Letter Words
MediumArrayHash TableStringGreedyCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a frequency count of the pairs of words and their reverses. We can form pairs that mirror each other to build the palindrome, and we can use one unpaired word in the center if available.
⚙️
Algorithm
4 steps- 1Step 1: Count occurrences of each word and its reverse using a HashMap.
- 2Step 2: For each unique word, calculate the maximum pairs that can be formed.
- 3Step 3: Check if there is any word that can be used as a center (i.e., a word that is its own reverse).
- 4Step 4: Sum the lengths of all pairs and add 2 if a center is used.
solution.py15 lines
1from collections import Counter
2
3def longestPalindrome(words):
4 count = Counter(words)
5 length = 0
6 center_added = False
7 for word, freq in count.items():
8 reverse_word = word[::-1]
9 if word == reverse_word:
10 length += (freq // 2) * 2
11 if freq % 2 == 1:
12 center_added = True
13 elif reverse_word in count:
14 length += min(freq, count[reverse_word]) * 2
15 return length + (2 if center_added else 0)ℹ
Complexity note: This complexity is linear because we only traverse the list of words a couple of times: once for counting and once for calculating the palindrome length. The space complexity is linear due to the HashMap storing the counts.
- 1A palindrome can be formed by pairing words that are reverses of each other.
- 2Words that are the same can contribute to the center of the palindrome.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.