Longest Palindrome by Concatenating Two Letter Words - Problem

Imagine you have a collection of two-letter word tiles and you want to create the longest possible palindrome by arranging them strategically!

You are given an array of strings words where each string consists of exactly two lowercase English letters. Your goal is to select some of these words and concatenate them in any order to form the longest possible palindrome.

Key Rules:

  • Each word can be used at most once
  • You can arrange the selected words in any order
  • The final string must read the same forwards and backwards

Example: Given ["lc","cl","gg"], you can create "lcggcl" which reads the same forwards and backwards, giving a length of 6.

Return the length of the longest palindrome you can create, or 0 if impossible.

Input & Output

example_1.py โ€” Basic Pairing
$ Input: words = ["lc","cl","gg"]
โ€บ Output: 6
๐Ÿ’ก Note: We can form "lcggcl" by pairing "lc" with "cl" and putting "gg" in the center. This creates a palindrome of length 6.
example_2.py โ€” Multiple Pairs
$ Input: words = ["ab","ty","yt","lc","cl","ab"]
โ€บ Output: 8
๐Ÿ’ก Note: We can pair "ab" with "ab" (both symmetric when reversed), "ty" with "yt", and "lc" with "cl" to get maximum length of 8.
example_3.py โ€” All Symmetric
$ Input: words = ["cc","ll","xx"]
โ€บ Output: 2
๐Ÿ’ก Note: All words are symmetric. We can use at most one in the center, so maximum length is 2.

Visualization

Tap to expand
Palindrome Construction StrategyStep 1: Word Classification"lc"asymmetric"cl"asymmetric"gg"symmetricThese pair together!Step 2: Palindrome AssemblyLeft SideCenterRight SidelcggclMirror symmetry"lcggcl" (length = 6)Maximum Length: 6
Understanding the Visualization
1
Count Word Inventory
Count how many of each two-letter word we have
2
Identify Symmetric vs Asymmetric
Words like 'aa' are symmetric, 'ab' needs 'ba' partner
3
Form Maximum Pairs
Pair asymmetric words with their reverse, pair symmetric words with themselves
4
Place Center Word
If any symmetric word remains unpaired, place it in center
Key Takeaway
๐ŸŽฏ Key Insight: Palindromes need symmetric structure - pair asymmetric words with their reverse, and use at most one symmetric word in the center

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through words array to count frequencies, then O(1) processing per unique word

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map stores at most n unique words in worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค words.length โ‰ค 105
  • words[i].length == 2
  • words[i] consists of lowercase English letters only
  • Each word can be used at most once
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.8K Views
Medium-High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen