Construct K Palindrome Strings - Problem

Given a string s and an integer k, determine whether you can use all the characters in s to construct exactly k non-empty palindrome strings.

A palindrome is a string that reads the same forward and backward. Return true if it's possible to construct k palindromes using all characters from s, otherwise return false.

Key constraints:

  • You must use all characters from the input string
  • Each palindrome must be non-empty
  • You need exactly k palindromes

Input & Output

Example 1 — Basic Case
$ Input: s = "annabelle", k = 2
Output: true
💡 Note: We can construct 2 palindromes: "anna" + "elble" or "anna" + "belle". Only one character 'b' has odd frequency, which is ≤ k=2.
Example 2 — Impossible Case
$ Input: s = "leetcode", k = 3
Output: false
💡 Note: Characters l, t, c, o, d all have odd frequencies (1 each). That's 5 odd frequencies > k=3, so impossible.
Example 3 — Edge Case
$ Input: s = "yzyzyzyzyzyzy", k = 2
Output: true
💡 Note: y appears 7 times, z appears 6 times. Only y has odd frequency, so 1 ≤ 2, possible.

Constraints

  • 1 ≤ k ≤ 105
  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters

Visualization

Tap to expand
Construct K Palindrome Strings INPUT String s = "annabelle" a n n a b e l l e Character Frequency: a: 2 n: 2 b: 1 e: 2 l: 2 Even Odd Total: 9 chars Input Values s = "annabelle", k = 2 ALGORITHM STEPS 1 Count Frequencies Count each character 2 Count Odd Frequencies oddCount = 1 (only 'b') 3 Check Conditions k <= len(s) AND oddCount <= k 4 Return Result Both conditions met: true Condition Checks: k <= len(s) 2 <= 9 [OK] oddCount <= k 1 <= 2 [OK] return (k <= n) AND (odd <= k) FINAL RESULT Possible K=2 Palindromes: Palindrome 1: a n n a "anna" Palindrome 2: e l b l e "elble" Output: true K palindromes possible! All 9 characters used Exactly 2 palindromes formed Key Insight: A palindrome can have at most ONE character with odd frequency (the middle character). Therefore, we need at least 'oddCount' palindromes to use all odd-frequency characters. We can form k palindromes if: (1) k is not more than total chars, AND (2) oddCount <= k. TutorialsPoint - Construct K Palindrome Strings | Optimal Solution O(n)
Asked in
Amazon 12 Google 8
28.5K Views
Medium Frequency
~15 min Avg. Time
891 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen