Closed mikewizeline closed 7 years ago
Another possibly more efficient solution to this problem is to count the number of occurrences of each character and then ensuring that the number of odd counts is less than or equal to one.
A sample implementation in Python:
from collections import Counter
def can_be_arranged_into_palindrome(string):
char_counts = Counter(string.lower())
odd_counts = sum(count % 2 for count in char_counts.values())
return odd_counts <= 1
Mike, could you update the problem description so it includes breaklines and // at the beginning? I usually copy/paste this to the candidates and I always have to format it on the fly.
Also, could you move the test cases upside the observations? so the structure would be something like Interviewer statement Test cases Observations -- Here you have 2 observations sections Solutions examples. -- Add this section
@zxul767 I'm not sure the approach you want to take will be correct, take the "noxno" for example, you are just ensuring that the number of odd counts is less than or equal to one, but you are not checking the order of the characters.
@legtzp Given my comment above about a possible confusion in the problem statement, do you still think the approach I took to solve the problem is incorrect?
@zxul767 nope your solution is correct indeed. Thanks for the clarification Willi :)
@zxul767 I like the solution, but the main idea is that candidates do what the Counter function does, and testing the solution it fails with phrases with odd spaces "Anita lava la tina". An expected solution would be like this:
def prepare_string(word):
word = word.lower()
word = word.replace(' ', '')
return word
def is_palindrome_unordered(word):
word = prepare_string(word)
if word is None or len(word) == 0:
return False
if len(word) == 1:
return True
word_dict = dict()
for character in word:
word_dict[character] = 1 if character not in word_dict.keys() else word_dict[character] + 1
odd_characters_count = 0;
for character_count in word_dict.values():
if character_count % 2 > 0:
odd_characters_count += 1
if odd_characters_count <= 1:
return True
return False
@mikewizeline If we stick to the problem statement (which doesn't mention anything about space characters being special) then "Anita lava la tina"
cannot be turned into a palindrome by a permutation of its characters, so the proposed solution is still correct. You'd need to specify that spaces are to be ignored in the problem statement if you expect that example to pass.
New exercise proposed, just to have more options while choosing for interviews.
@bobmazanec @vidalon