Construct K Palindrome Strings - Problem
Imagine you're a word puzzle master tasked with creating k palindrome strings using all the characters from a given string s. A palindrome reads the same forwards and backwards, like "racecar" or "level".
Your challenge is to determine if it's possible to redistribute all characters from the input string to form exactly k non-empty palindromes. Each character must be used exactly once, and you need to create exactly k palindromic strings.
Examples:
- With string
"annabelle"andk=2, you could form["anna", "belleb"] - With string
"abc"andk=3, you could form["a", "b", "c"](single characters are palindromes) - With string
"abc"andk=2, it's impossible since we'd need at least one multi-character palindrome, but we only have unique characters
Return true if the redistribution is possible, false otherwise.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "annabelle", k = 2
โบ
Output:
true
๐ก Note:
We can construct 2 palindromes: "anna" (using a,n,n,a) and "belleb" (using b,e,l,l,e,b). Character frequencies: a:2, n:2, b:1, e:2, l:2. Only 'b' has odd frequency (1), and 1 โค 2, so it's possible.
example_2.py โ Impossible Case
$
Input:
s = "leetcode", k = 3
โบ
Output:
false
๐ก Note:
Character frequencies: l:1, e:3, t:1, c:1, o:1, d:1. We have 5 characters with odd frequencies, but k=3. Since each palindrome can have at most 1 odd-frequency character, we need at least 5 palindromes, not 3.
example_3.py โ Edge Case - All Singles
$
Input:
s = "abc", k = 3
โบ
Output:
true
๐ก Note:
We can form 3 single-character palindromes: "a", "b", "c". Each character appears once (odd frequency), and we have exactly 3 odd-frequency characters for k=3 palindromes.
Visualization
Tap to expand
Understanding the Visualization
1
Count Materials
Count how many of each character (building material) we have
2
Find Unpaired Items
Characters with odd counts are 'unpaired' - they need to go in the center of palindromes
3
Check Distribution
Since each palindrome can have at most one center piece, we need odd_count โค k
Key Takeaway
๐ฏ Key Insight: Just like each symmetric building can have at most one unique centerpiece, each palindrome can contain at most one character with an odd frequency. The solution elegantly reduces to: count odd-frequency characters and check if โค k.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string to count character frequencies
โ Linear Growth
Space Complexity
O(1)
Only need space for at most 26 character counts (constant space)
โ Linear Space
Constraints
- 1 โค k โค s.length โค 105
- s consists of lowercase English letters only
- Each palindrome must be non-empty
- All characters from s must be used exactly once
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code