Construct K Palindrome Strings (LeetCode 1400): Solution and Explanation
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
- If
k > len(s), return false. - Count how many times each of the 26 letters appears.
- Let
oddbe the number of letters whose count is odd. - Return
odd <= k.
Step-by-step example
s = "annabelle", k = 2
- len(s) = 9 and k = 2, so k is not too large.
- The counts are a = 2, b = 1, e = 2, l = 2, n = 2.
- Only b has an odd count, so odd = 1.
- 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 <= k1class Solution {
2 public boolean canConstruct(String s, int k) {
3 if (k > s.length()) {
4 return false;
5 }
6 int[] counts = new int[26];
7 for (char ch : s.toCharArray()) {
8 counts[ch - 'a']++;
9 }
10 int odd = 0;
11 for (int c : counts) {
12 odd += c % 2;
13 }
14 return odd <= k;
15 }
16}1class Solution {
2public:
3 bool canConstruct(string s, int k) {
4 if (k > (int)s.size()) {
5 return false;
6 }
7 vector<int> counts(26, 0);
8 for (char ch : s) {
9 counts[ch - 'a']++;
10 }
11 int odd = 0;
12 for (int c : counts) {
13 odd += c % 2;
14 }
15 return odd <= k;
16 }
17};Time and space complexity
O(n)
One pass counts the letters, and checking 26 counters is constant work.
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. Withs = "abba"andk = 5there are no odd letters, but five non-empty strings cannot be made from four letters. - Thinking
odd == kis 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.