Construct K Palindrome Strings Problem
Description
LeetCode Problem 1400.
Given a string s and an integer k, return true if you can use all the characters in s to construct non-empty k palindrome strings or false otherwise.
Example 1:
Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"
Example 2:
Input: s = "leetcode", k = 3
Output: false
Explanation: It is impossible to construct 3 palindromes using all the characters of s.
Example 3:
Input: s = "true", k = 4
Output: true
Explanation: The only possible solution is to put each character in a separate string.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters.1 <= k <= 10^5
Solution
Approach: Count Letters with an Odd Count
Two facts decide the answer:
- Each palindrome needs at least one character. If
len(s) < k, there are not enough characters to go around, so returnfalse. - A palindrome contains at most one letter with an odd count, the one in its middle. Every letter that occurs an odd number of times in
sleaves one copy that cannot be paired, so it needs a palindrome of its own to sit in the middle. Withoddsuch letters we needodd <= k.
These two conditions are also enough. Put each odd-count letter's leftover copy as the middle of its own palindrome, which uses odd of the k strings. Everything left over can be split into equal pairs. Pairs can be added to any palindrome (one copy at each end), and a pair of letters is itself a palindrome, as is a single character. So we can fill the remaining k - odd strings with pairs and single characters as needed. Since len(s) >= k, there is always enough material to make every string non-empty.
In Example 2, "leetcode" has odd counts for l, t, c, o and d, five letters, so it cannot be split into 3 palindromes. In Example 3, "true" has four characters, each in its own one-letter palindrome.
Complexity: O(n) time to count the letters and O(1) space for 26 counters.
from collections import Counter
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k: # every palindrome needs at least one character
return False
odd = sum(v % 2 for v in Counter(s).values())
return odd <= k # each palindrome can hold at most one odd-count letter, in its middle