This is a solution to exercise 1.4 from Cracking the Coding Interview written using Python 3.
Given a string, write a function to check if it is a permutation of a palindrome.
Example: 'Tact Coa'
Output: True (permutations: "taco cat", "atco cta", etc.)
I wanted to get feedback on making my code clearer and more pythonic. I believe my code has time complexity \$O(n)\$ and space complexity \$ O(n)\$ is that correct? If so, is there any way to improve on either the space or time complexity?
from collections import Counter
def is_palindrome_permutation(data: str) -> bool:
"""Given a string, check if it is a permutation of a palindrome."""
data = data.lower().replace(' ', '')
num_odd = sum(1 for char, freq in Counter(data).items() if char != ' ' and freq % 2 == 1)
# Check for two types of palindromes , 1) Odd Length (e.g. abc cba) 2) Even Length (e.g. abc d cba)
if num_odd == 1 and len(data) % 2 == 1 or num_odd == 0 and len(data) % 2 == 0:
return True
else:
return False
Test
datum = 'Tac4t co@A @4'
print(is_palindrome_permutation(datum))
Result
True
Test
datum = 'Tac4t co@A @4s'
print(is_palindrome_permutation(datum))
Result
False