Maximum Palindromes After Operations - Problem
Imagine you have a collection of string words and magical powers to rearrange any characters between them! ๐ญ
You're given an array of strings words, and you can perform an unlimited number of character swaps. In each operation, you can:
- Choose any two strings (they can be the same string)
- Pick any character position in each string
- Swap those two characters
Your goal is to determine the maximum number of palindromes you can create from these words after performing optimal swaps.
Example: If you have ["abc", "def"], you could swap characters to potentially create ["aba", "dfd"] - two palindromes!
The key insight is that since you can swap any characters between any words, what matters is the total count of each character across all words, not their initial positions.
Input & Output
example_1.py โ Basic Case
$
Input:
words = ["abde", "cxyz", "abc"]
โบ
Output:
2
๐ก Note:
We have characters: a=2, b=2, c=2, d=1, e=1, x=1, y=1, z=1. This gives us 3 pairs and 5 singles. Sorting word lengths: [3,4,4]. We can form 2 palindromes by using pairs optimally: one 3-length palindrome (1 pair + 1 single) and one 4-length palindrome (2 pairs).
example_2.py โ All Same Length
$
Input:
words = ["abc", "def", "ghi"]
โบ
Output:
0
๐ก Note:
All characters appear only once, giving us 0 pairs and 9 singles. Each word needs at least 1 pair to form a palindrome of length 3, but we have no pairs available. Result: 0 palindromes.
example_3.py โ Perfect Palindromes
$
Input:
words = ["aab", "baa", "cc"]
โบ
Output:
3
๐ก Note:
We have a=4, b=2, c=2, giving us 4 pairs and 0 singles. Word lengths [3,3,2] all can be formed into palindromes: length 3 needs 1 pair + 1 single (we can use 2 pairs as substitute), length 3 needs 1 pair + 1 single, length 2 needs 1 pair. Total: 3 palindromes.
Constraints
- 1 โค words.length โค 105
- 1 โค words[i].length โค 100
- words[i] consists of lowercase English letters only
- Key insight: Since any character can be moved to any position in any word, only total character counts matter
Visualization
Tap to expand
Understanding the Visualization
1
Inventory Count
Count all your cookies by letter type across all jars
2
Resource Planning
Calculate how many 'pairs' and 'single' cookies you have
3
Smart Assignment
Start with the smallest jars - they need fewer cookies to form palindromes
4
Maximize Output
Continue until you run out of cookies or jars
Key Takeaway
๐ฏ Key Insight: Since characters can be freely redistributed, we only care about total character counts. The greedy strategy of filling shortest words first maximizes palindromes because they require fewer resources.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code