#1400
Construct K Palindrome Strings
MediumHash TableStringGreedyCountingHash MapCounting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution focuses on counting character frequencies and determining the minimum number of palindromes that can be formed based on odd character counts. This is efficient and avoids unnecessary partitioning.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in the string.
- 2Step 2: Count how many characters have odd frequencies.
- 3Step 3: If the number of odd frequencies is greater than k, return false; otherwise, return true.
solution.py9 lines
1# Full working Python code
2from collections import Counter
3
4def can_construct_k_palindromes(s, k):
5 if len(s) < k:
6 return False
7 freq = Counter(s)
8 odd_count = sum(1 for count in freq.values() if count % 2 != 0)
9 return odd_count <= kℹ
Complexity note: The complexity is linear because we only traverse the string once to count frequencies and then check the counts, leading to efficient performance.
- 1If the length of the string is less than k, it's impossible to form k non-empty strings.
- 2The number of characters with odd frequencies determines the minimum number of palindromes that can be formed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.