{x}
blog image

Construct K Palindrome Strings

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 <= 105
  • s consists of lowercase English letters.
  • 1 <= k <= 105

Solution Explanation: Construct K Palindrome Strings

This problem asks whether it's possible to construct k non-empty palindrome strings using all characters from a given string s. The solution leverages a greedy approach combined with counting character frequencies.

Approach:

  1. Base Case: If the length of s is less than k, it's impossible to create k non-empty strings, so we return false.

  2. Character Counting: We use a hash table (or an array in the code examples) to count the occurrences of each character in s. This efficiently determines the frequency of each character.

  3. Odd Character Count: We count the number of characters that appear an odd number of times. These characters require special handling because a palindrome must have an even number of each character (except possibly one character in the middle).

  4. Feasibility Check: The key insight is that each character with an odd count necessitates at least one palindrome string to accommodate it. Therefore, if the number of characters with odd counts (x) exceeds k, it's impossible to create k palindromes, and we return false. Otherwise, we can create k palindromes, and we return true.

Time Complexity: O(n), where n is the length of string s. Character counting and the final check both take linear time.

Space Complexity: O(C), where C is the size of the character set (26 for lowercase English letters). This is the space used for the character count hash table (or array). This space complexity is considered constant in most cases as the character set is fixed.

Code Examples (with explanations):

Python:

from collections import Counter
 
class Solution:
    def canConstruct(self, s: str, k: int) -> bool:
        if len(s) < k:
            return False
        cnt = Counter(s)  #Efficiently counts character frequencies
        odd_count = sum(1 for v in cnt.values() if v % 2 != 0) #Counts characters with odd frequencies
        return odd_count <= k #Checks feasibility

Java:

class Solution {
    public boolean canConstruct(String s, int k) {
        int n = s.length();
        if (n < k) {
            return false;
        }
        int[] cnt = new int[26]; //Array for character counts (index represents character 'a' to 'z')
        for (int i = 0; i < n; ++i) {
            cnt[s.charAt(i) - 'a']++;
        }
        int oddCount = 0;
        for (int count : cnt) {
            if (count % 2 != 0) {
                oddCount++;
            }
        }
        return oddCount <= k;
    }
}

C++:

class Solution {
public:
    bool canConstruct(string s, int k) {
        if (s.length() < k) return false;
        int cnt[26] = {0}; //Array for character counts
        for (char c : s) cnt[c - 'a']++;
        int odd_count = 0;
        for (int count : cnt) if (count % 2) odd_count++;
        return odd_count <= k;
    }
};

Go:

func canConstruct(s string, k int) bool {
    if len(s) < k {
        return false
    }
    cnt := [26]int{}
    for _, c := range s {
        cnt[c-'a']++
    }
    oddCount := 0
    for _, count := range cnt {
        if count%2 != 0 {
            oddCount++
        }
    }
    return oddCount <= k
}

The other languages (TypeScript, etc.) follow a similar pattern. The core logic remains consistent across all implementations: efficiently count character frequencies, determine the number of characters with odd counts, and check if this number is less than or equal to k.