Maximum Palindromes After Operations

Medium Arrays & Hashing Greedy

Maximum Palindromes After Operations is a medium arrays & hashing problem solved with the greedy pattern. The best approach, optimal (greedy with counting by cost), runs in O(L + n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every set of words) up.

Problem

You are given an array words of n strings made of lowercase English letters.

You may repeat the following operation as many times as you like (including zero times): pick any two character positions, either in the same word or in two different words, and swap the two characters. The words keep their lengths; only the letters move around.

Return the largest number of words that can be palindromes at the same time after some sequence of these operations. A palindrome reads the same from left to right as from right to left.

Examples

Example 1

Input
words = ["aab","bcc","ca"]
Output
3
Why
Together the words hold three a's, two b's and three c's. Rearranged as "aca", "cac" and "bb" (same lengths 3, 3 and 2), all three words are palindromes.

Example 2

Input
words = ["abcd","ab","cc"]
Output
2
Why
The letters form only 3 matching pairs (aa, bb and cc). The two short words need one pair each and "abcd" alone needs two, so not all three can be palindromes. For example "aa" and "cc" work, with "bcdb" left over.

Example 3

Input
words = ["xy","zw","q"]
Output
1
Why
All letters are different, so there is no pair at all. Only the one-letter word can be a palindrome.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 100
  • words[i] contains only lowercase English letters

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 22 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every set of words)O(2^n * n + L)O(1)
Greedy (shortest words first)O(L + n log n)O(n)
Optimal (greedy with counting by cost)O(L + n)O(1)

1Brute force (try every set of words)

TimeO(2^n * n + L)There are 2^n subsets and each is summed in O(n); counting the letters reads all L characters once.
SpaceO(1)26 letter counts and a few integers.

Because characters can be swapped anywhere, the words only share one pool of letters. A word of length L is a palindrome when its first L / 2 positions mirror its last L / 2, so it needs L / 2 pairs of equal letters, plus any single letter in the middle when L is odd. Let P be the number of pairs in the pool: the sum over the 26 letters of count / 2. A chosen set of words can all become palindromes exactly when the pairs they need add up to at most P. Give each chosen word its pairs; every other position, including the middle letters, can take whatever letters are left, since the number of letters always equals the number of positions. So try every subset of the words and keep the largest one whose need fits in P.

  1. Count every letter over all words and set P = the sum of count / 2.
  2. For every subset (bit mask) of the n words, add up words[i].length / 2 over the chosen words.
  3. If that need is at most P, the subset works: update the best size.
  4. Return the best size.
class Solution {
    public int maxPalindromesAfterOperations(String[] words) {
        int n = words.length;
        int[] cnt = new int[26];
        for (String w : words)
            for (char c : w.toCharArray()) cnt[c - 'a']++;
        int pairs = 0;
        for (int c : cnt) pairs += c / 2;
        int best = 0;
        for (int mask = 0; mask < (1 << n); mask++) {
            int need = 0;
            for (int i = 0; i < n; i++)
                if ((mask >> i & 1) == 1) need += words[i].length() / 2;
            if (need <= pairs) best = Math.max(best, Integer.bitCount(mask));
        }
        return best;
    }
}

2Greedy (shortest words first)

TimeO(L + n log n)Counting reads all L characters; sorting the n costs takes O(n log n); the final loop is O(n).
SpaceO(n)The array of n costs (plus 26 letter counts).

The subset test only looks at the total need, so this is a budget problem: P pairs to spend, word i costs words[i].length / 2, and we want as many words as possible. Cheapest first is optimal. If some best set skips a cheaper word but takes a more expensive one, swapping them keeps the size and does not raise the cost. So sort the costs in increasing order and take words while the remaining pairs cover the next cost. Words of length 1 cost nothing and are always taken.

  1. Count every letter and set pairs = the sum of count / 2.
  2. Put words[i].length / 2 for every word into an array need and sort it in increasing order.
  3. For each value h in need: if h > pairs, stop. Otherwise pairs -= h and count one more palindrome.
  4. Return the count.
class Solution {
    public int maxPalindromesAfterOperations(String[] words) {
        int[] cnt = new int[26];
        for (String w : words)
            for (char c : w.toCharArray()) cnt[c - 'a']++;
        int pairs = 0;
        for (int c : cnt) pairs += c / 2;
        int n = words.length;
        int[] need = new int[n];
        for (int i = 0; i < n; i++) need[i] = words[i].length() / 2;
        Arrays.sort(need);
        int done = 0;
        for (int h : need) {
            if (h > pairs) break;
            pairs -= h;
            done++;
        }
        return done;
    }
}

3Optimal (greedy with counting by cost)

TimeO(L + n)Counting letters reads all L characters, filling the buckets visits each word once, and the walk over 51 costs is constant.
SpaceO(1)26 letter counts and 51 buckets, whatever the input size.

Same greedy, without the sort. A word is at most 100 letters long, so its cost is between 0 and 50. Count how many words have each cost, then walk the costs from 0 upward. At cost h, take as many of those words as the pairs allow: all of them, or pairs / h if that is fewer. As soon as some word of cost h has to be left out, every remaining word costs at least h too, so stop.

  1. Count every letter and set pairs = the sum of count / 2.
  2. bucket[h] = the number of words with length / 2 == h, for h from 0 to 50.
  3. For h = 0, 1, ..., 50: take = bucket[h] when h == 0, else min(bucket[h], pairs / h). Add take to the answer and subtract take * h from pairs.
  4. If take < bucket[h], stop early. Return the answer.
class Solution {
    public int maxPalindromesAfterOperations(String[] words) {
        int[] cnt = new int[26];
        int[] bucket = new int[51];
        for (String w : words) {
            for (char c : w.toCharArray()) cnt[c - 'a']++;
            bucket[w.length() / 2]++;
        }
        int pairs = 0;
        for (int c : cnt) pairs += c / 2;
        int done = 0;
        for (int h = 0; h <= 50; h++) {
            int take = h == 0 ? bucket[0] : Math.min(bucket[h], pairs / h);
            done += take;
            pairs -= take * h;
            if (take < bucket[h]) break;
        }
        return done;
    }
}

Edge cases to test

  • A single word: the answer is 0 or 1, depending on whether its own letters allow a palindrome ("ab" cannot, "aab" can)
  • Words of length 1 need no pair at all and always count
  • No letter appears twice anywhere: only the words of length 1 can be palindromes
  • Odd-length words need a middle letter, but any leftover letter can serve, so only pairs are ever the bottleneck
  • Many short words and one very long word: filling the short words first gives the larger count
  • All letters the same: every word can be a palindrome, the answer is words.length

Hints

Hint 1

Since letters can move anywhere, only the total count of each letter matters, not which word it starts in.

Hint 2

A palindrome of length L is made of L / 2 matching pairs (mirrored around the middle) plus one free middle letter when L is odd.

Hint 3

Count the pairs P available across all words. A set of words can all be palindromes exactly when their L / 2 values add up to at most P.

Hint 4

To fit as many words as possible under the budget P, take the words that need the fewest pairs first.

FAQ

What is the best time complexity for Maximum Palindromes After Operations?

Optimal (greedy with counting by cost) runs in O(L + n) time and O(1) extra space. Counting letters reads all L characters, filling the buckets visits each word once, and the walk over 51 costs is constant.

Which pattern does Maximum Palindromes After Operations use?

It is a arrays & hashing problem that uses the greedy pattern. Other problems with the same pattern: Integer to Roman, Jump Game II, Jump Game.

Is there a brute force solution for Maximum Palindromes After Operations?

Yes. Brute force (try every set of words) takes O(2^n * n + L) time and O(1) space. Because characters can be swapped anywhere, the words only share one pool of letters.

Which edge cases should I test for Maximum Palindromes After Operations?

A single word: the answer is 0 or 1, depending on whether its own letters allow a palindrome ("ab" cannot, "aab" can); Words of length 1 need no pair at all and always count; No letter appears twice anywhere: only the words of length 1 can be palindromes; Odd-length words need a middle letter, but any leftover letter can serve, so only pairs are ever the bottleneck; Many short words and one very long word: filling the short words first gives the larger count; All letters the same: every word can be a palindrome, the answer is words.length.