Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created January 11, 2025 22:33
Show Gist options
  • Save Ifihan/c545cd35eca76158cb562641b87b2759 to your computer and use it in GitHub Desktop.
Save Ifihan/c545cd35eca76158cb562641b87b2759 to your computer and use it in GitHub Desktop.
Construct K Palindrome Strings

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n) for the length of s.
  • Space: O(1).
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment