I used Python's Counter
to create a hashmap that stored the frequency of each character in the string. Then I iterated through the hashmap and counted all the characters with odd occurrences. This value, was called odd_count
, and it was to measure whether constructing k
palindromes was feasible.
Next, I implemented the conditions to if k
was greater than the length of the string because, it would be impossible to construct k
palindromes. Also, I compared odd_count
with k
, knowing that k
must be at least as large as odd_count
since each palindrome can only handle one odd-frequency character.
Then I return True
if the conditions were satisfied, showing thatk
palindromes was possible.
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if k > len(s):
return False
freq = Counter(s)
odd_count = sum(1 for count in freq.values() if count % 2 != 0)
return odd_count <= k
- Time: O(n) for the length of
s
. - Space: O(1).
