LeetCode Entry
409. Longest Palindrome
Max palindrome length from chars
409. Longest Palindrome easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/628
Problem TLDR
Max palindrome length from chars #easy
Intuition
Don’t mistaken this problem with find the longest palindrome, because this time we need to build one. (I have spent 5 minutes solving the wrong problem)
To build a palindrome, we need even counts of chars and at most one odd.
Approach
- we can use
groupBy,sumByandany f & 1operation will convert anyoddnumber into1
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\), but O(n) for the
groupBysolution, which can be optimized
Code
fun longestPalindrome(s: String): Int =
s.groupBy { it }.values.run {
2 * sumBy { it.size / 2 } +
if (any { it.size % 2 > 0 }) 1 else 0
}
pub fn longest_palindrome(s: String) -> i32 {
let (mut freq, mut res, mut o) = (vec![0;128], 0, 0);
for b in s.bytes() { freq[b as usize] += 1 }
for f in freq { o |= f & 1; res += f / 2 }
2 * res + o
}