Maximum Palindromes After Operations - Problem
You are given a 0-indexed string array words having length n and containing 0-indexed strings.
You are allowed to perform the following operation any number of times (including zero):
- Choose integers
i,j,x, andysuch that0 <= i, j < n,0 <= x < words[i].length,0 <= y < words[j].length, and swap the characterswords[i][x]andwords[j][y].
Return an integer denoting the maximum number of palindromes words can contain, after performing some operations.
Note: i and j may be equal during an operation.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["abc","car","a"]
›
Output:
2
💡 Note:
We have characters: a,b,c,c,a,r,a → {a:3, b:1, c:2, r:1}. Pairs=3, odds=1. Words sorted by length: [3,3,1]. First two words need 1 pair each, so we can form 2 palindromes like "aca" and "rcr".
Example 2 — All Same Length
$
Input:
words = ["ab","ty","yt"]
›
Output:
2
💡 Note:
Characters: a,b,t,y,y,t → {a:1, b:1, t:2, y:2}. Pairs=2, odds=2. Each word needs 1 pair. We can form 2 palindromes like "ty" and "yt", but "ab" cannot be formed into palindrome with remaining characters.
Example 3 — Single Character Words
$
Input:
words = ["a","b","a"]
›
Output:
2
💡 Note:
Characters: a,b,a → {a:2, b:1}. Pairs=1, odds=1. All words have length 1 (need 0 pairs each). We can form 2 palindromes using the 2 'a' characters, but 'b' forms the third palindrome too. Total: 3, but wait - we have 2 odds available, so answer is 2.
Constraints
- 1 ≤ words.length ≤ 105
- 1 ≤ words[i].length ≤ 105
- sum(words[i].length) ≤ 2 × 105
- words[i] consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input Words
Array of strings with swappable characters
2
Global Pool
All characters can be redistributed freely
3
Form Palindromes
Maximum palindromes using optimal character assignment
Key Takeaway
🎯 Key Insight: Since characters can be swapped freely, use greedy assignment by word length to maximize palindromes
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code