Maximum Palindromes After Operations

Medium

Topics
ArrayStringHash TableGreedySortingCounting

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

the shared letter poola ×2b ×4c ×2
word lengths, shortest first224
pairs each length needs112
can be made a palindrome
Of these 3 words, 3 can be palindromes at once. Swaps move characters between any two words, so which word a letter starts in is irrelevant — what is fixed is the shared pool above and the length of each container. A word of length L needs L divided by 2 pairs of matching letters, and the pool holds 4; an odd middle character can be anything, so pairs are the only thing that runs out.
Lengths are shown shortest first, which is not the input order.
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

the shared letter poola ×2b ×2c ×1
word lengths, shortest first23
pairs each length needs11
can be made a palindrome
Input:  words = ["abc","ab"]
Output: 2
Explanation: There are enough matching characters to make both, for instance "aca" and "bb".

Example 3

the shared letter poola ×1c ×1d ×1e ×1f ×1
word lengths, shortest first122
pairs each length needs01
can be made a palindromecannot
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

  1. Count every letter across all words, and sum count / 2 over the letters to get the number of available pairs.
  2. Collect the word lengths and sort them ascending.
  3. Walk the lengths. Each word needs length / 2 pairs.
  4. If enough pairs remain, spend them and count the word. If not, stop — every later word is at least as expensive.
  5. 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 made
SensAI
Beta
Tap the mic to stop voice mode