[Python] 2 lines with counter + Oneliner, explained
Note, that it every palindrome we need to use every letter even number of times, maybe except one letter in the middle. Note also, that this condition is also s
Note, that it every palindrome we need to use every letter `even` number of times, maybe except one letter in the middle. Note also, that this condition is also sufficient: if we have frequencies for each letter which are even and one frequence is odd, we can always create palindrome. For example let us have `aaaaaa`, `c`, `bbbb`, then we create `aaabbcbbaaa`.\n\nSo, all we need to do is to count frequencies of each letter and take as much letters as possible. There are two possible cases:\n1. If we have only `zero` or `one` letters with odd frequencies, then we can use all the letters.\n2. If we have `k>1` letters with odd frequencies, we need to remove exactly `k-1` letter to build palindrome.\n\n**Complexity**: space complexity is `O(k)`, where `k` is size of used alphabet. Time complexity is `O(n)`, where `n` is length of our string: we process it once to get counter, then we find reminders of frequencies modulo `2` in `O(k)`.\n\n\n```\nclass Solution:\n    def longestPalindrome(self, s):\n        odds = sum([freq % 2 for _,freq in Counter(s).items()])\n        return len(s) if odds <=1 else len(s) - odds + 1 \n```\n\n### Oneliner\nThe same logic can be written as oneliner\n```return len(s) if (o:=sum([f%2 for _,f in Counter(s).items()])) <=1 else len(s)-o+1```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
[]