Construct K Palindrome Strings (LeetCode 1400): Solution and Explanation

Medium
Hash Table
String
Greedy
Counting

Decide whether all the characters of s can be split into exactly k non-empty palindromes.

Intuition

A palindrome reads the same in both directions, so its letters come in mirrored pairs. The only exception is the single middle character of an odd-length palindrome.

So any letter that appears an odd number of times leaves one copy unpaired, and that copy must be the center of some palindrome. Two odd letters cannot share a center, so every odd letter needs its own palindrome. That gives a lower bound: at least odd palindromes.

The upper bound is the length: every palindrome needs at least one letter, so k cannot exceed len(s). Anything in between works, because you can always split a single letter off into its own palindrome, or split a pair into two one-letter palindromes, to raise the count by one at a time.

Approach: Count odd letters

  1. If k > len(s), return false.
  2. Count how many times each of the 26 letters appears.
  3. Let odd be the number of letters whose count is odd.
  4. Return odd <= k.

Step-by-step example

s = "annabelle", k = 2
  1. len(s) = 9 and k = 2, so k is not too large.
  2. The counts are a = 2, b = 1, e = 2, l = 2, n = 2.
  3. Only b has an odd count, so odd = 1.
  4. 1 <= 2, so the answer is true. For example "anbna" and "elle".

Code: Python, Java, C++

1class Solution:
2    def canConstruct(self, s: str, k: int) -> bool:
3        if k > len(s):
4            return False
5        counts = [0] * 26
6        for ch in s:
7            counts[ord(ch) - ord('a')] += 1
8        odd = sum(c % 2 for c in counts)
9        return odd <= k
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass counts the letters, and checking 26 counters is constant work.

Space

O(1)

Only 26 counters are stored, whatever the input size.

Other approaches

Parity bitmask (time O(n), space O(1))

Flip bit ch - 'a' of an integer for each character; the number of set bits at the end is the number of odd letters. Same idea, one integer of state.

Common mistakes

  • Forgetting the k > len(s) check. With s = "abba" and k = 5 there are no odd letters, but five non-empty strings cannot be made from four letters.
  • Thinking odd == k is required. Having more palindromes than odd letters is fine, since extra ones can be formed by splitting pairs or single letters.
  • Trying to actually build the palindromes. Only the counts matter, so there is no need to construct anything.

Frequently asked questions

Why is odd <= k enough?

Start with odd palindromes, one per odd letter, and put all pairs into them. You can then raise the number of palindromes one at a time by splitting off a single letter, until you reach k, as long as k <= len(s).

What if there are no odd letters?

Then odd = 0 and the only limit is k <= len(s). For example "abba" can form 1, 2, 3 or 4 palindromes.

Does the order of characters in s matter?

No. You may arrange the characters freely, so only how many times each letter appears matters.

What are the time and space costs?

O(n) time to count, and O(1) space for 26 counters.