Maximum Palindromes After Operations
Medium
Topics
You may repeatedly pick any two positions in any two words of words — the same word or different ones — and swap the characters there. There is no limit on the number of swaps.
Return the largest number of words that can all be palindromes at the same time.
Example 1
Input: words = ["abbb","ba","cc"] Output: 3 Explanation: Swapping characters around can make all three palindromes at once, for instance "bbbb", "aa" and "cc".
Example 2
Input: words = ["abc","ab"] Output: 2 Explanation: There are enough matching characters to make both, for instance "aca" and "bb".
Example 3
Input: words = ["cd","ef","a"] Output: 1 Explanation: Every letter appears once, so no pair exists and only the single-character word can be a palindrome.
Constraints
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 100
- words[i] consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
Swaps move characters anywhere, so which word a character starts in does not matter. What is fixed is the multiset of all characters across every word, and the length of each word. The question becomes: given that pool of letters, how many of these word-shaped containers can be filled palindromically?
A word of length L is a palindrome when its characters can be arranged symmetrically, which needs L / 2 pairs of equal letters, plus one leftover character in the middle if L is odd. The middle character can be anything at all, so it costs nothing scarce.
So the only scarce resource is pairs. Count, over the whole pool, how many pairs exist: for each letter that is the count divided by two, discarding the odd one out.
Then spend those pairs on the shortest words first. A word of length L costs L / 2 pairs, and satisfying a cheap word before an expensive one can never reduce the total count — so sorting the lengths ascending and taking words while the pairs last gives the maximum. The odd middles never run out, because the total character count is exactly the total length.
Approach
- Count every letter across all words, and sum
count / 2over the letters to get the number of available pairs. - Collect the word lengths and sort them ascending.
- Walk the lengths. Each word needs
length / 2pairs. - If enough pairs remain, spend them and count the word. If not, stop — every later word is at least as expensive.
- Return how many words were counted.
Walkthrough
words = ["abbb","ba","cc"]
pool of letters: a:2 b:4 c:2
pairs available: 2/2 + 4/2 + 2/2 = 1 + 2 + 1 = 4
lengths sorted ascending: 2, 2, 4
length 2 needs 1 pair -> 4 - 1 = 3 pairs left, count 1
length 2 needs 1 pair -> 3 - 1 = 2 pairs left, count 2
length 4 needs 2 pairs -> 2 - 2 = 0 pairs left, count 3
answer 3
and a concrete arrangement: "bbbb", "aa", "cc"
words = ["cd","ef","a"]
pool: a:1 c:1 d:1 e:1 f:1
pairs available: 0
lengths sorted: 1, 2, 2
length 1 needs 0 pairs -> count 1
length 2 needs 1 pair -> none left, stop
answer 1
why shortest first
with 2 pairs and lengths 4 and 2, taking the length-4
word costs both pairs for one word. Taking the length-2
word costs one pair, leaving one -- not enough for the
other, so one word either way. But with 3 pairs and
lengths 6, 2, 2: shortest-first gets both 2s (1 pair
each) and then has 1 pair left, so 2 words; taking the
6 first spends all 3 for a single word.Complexity
- Time — O(total characters + w log w): counting is linear in the input; the sort is over the w word lengths.
- Space — O(w): the lengths, plus a fixed 26-entry count table.
Common Pitfalls
- Treating each word separately. Swaps cross words, so the letters form one shared pool.
- Counting characters rather than pairs. A word of length 4 needs 2 pairs, not 4 characters of a particular kind.
- Spending pairs on the longest words first, which maximises cost per word rather than the number of words.
- Worrying about which letter fills the odd middle. Any letter works, and the arithmetic guarantees one is spare.
- Forgetting that a length-1 word is already a palindrome and costs nothing.
Full Solution — all languages
class Solution:
def maxPalindromesAfterOperations(self, words):
counts = {}
for word in words:
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
# Pairs are the only scarce resource. An odd middle character can be
# anything, and the totals always leave enough of those.
pairs = sum(c // 2 for c in counts.values())
made = 0
for length in sorted(len(w) for w in words):
need = length // 2
if need > pairs:
break # every later word is at least as expensive
pairs -= need
made += 1
return madeimport java.util.*;
class Solution {
public int maxPalindromesAfterOperations(String[] words) {
int[] counts = new int[26];
for (String word : words) {
for (int i = 0; i < word.length(); i++) counts[word.charAt(i) - 'a']++;
}
int pairs = 0;
for (int c : counts) pairs += c / 2;
int[] lengths = new int[words.length];
for (int i = 0; i < words.length; i++) lengths[i] = words[i].length();
Arrays.sort(lengths);
int made = 0;
for (int length : lengths) {
int need = length / 2;
if (need > pairs) break;
pairs -= need;
made++;
}
return made;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxPalindromesAfterOperations(vector<string>& words) {
unordered_map<char, int> counts;
for (const string& word : words) {
for (char ch : word) counts[ch]++;
}
int pairs = 0;
for (auto& kv : counts) pairs += kv.second / 2;
vector<int> lengths;
for (const string& w : words) lengths.push_back((int)w.size());
sort(lengths.begin(), lengths.end());
int made = 0;
for (int length : lengths) {
int need = length / 2;
if (need > pairs) break;
pairs -= need;
made++;
}
return made;
}
};/**
* @param {string[]} words
* @return {number}
*/ var maxPalindromesAfterOperations = function(words) {
const counts = new Map();
for (const word of words) {
for (const ch of word) counts.set(ch, (counts.get(ch) || 0) + 1);
}
let pairs = 0;
for (const c of counts.values()) pairs += Math.floor(c / 2);
const lengths = words.map((w) => w.length).sort((x, y) => x - y);
let made = 0;
for (const length of lengths) {
const need = Math.floor(length / 2);
if (need > pairs) break;
pairs -= need;
made++;
}
return made;
};