Construct K Palindrome Strings — LeetCode 1400 Python Solution
MediumGreedyHash TableStringCounting
- Problem
- #1400
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- s = "annabelle", k = 2
- Output
- true
- Explanation
- You can construct two palindromes using all characters in s.
Python solution
Python
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k:
return False
cnt = Counter(s)
return sum(v & 1 for v in cnt.values()) <= kComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1400. Construct K Palindrome Strings is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1400. Construct K Palindrome Strings?
- LeetCode 1400. Construct K Palindrome Strings is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1400. Construct K Palindrome Strings?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1400. Construct K Palindrome Strings?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 1400. Construct K Palindrome Strings cover?
- LeetCode 1400. Construct K Palindrome Strings is tagged Greedy, Hash Table, String and Counting on LeetCode.