409. Longest Palindrome LeetCode Solution

In this guide, you will get 409. Longest Palindrome LeetCode Solution with the best time and space complexity. The solution to Longest Palindrome problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Longest Palindrome solution in C++
  4. Longest Palindrome solution in Java
  5. Longest Palindrome solution in Python
  6. Additional Resources
409. Longest Palindrome LeetCode Solution image

Problem Statement of Longest Palindrome

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome.

Example 1:

Input: s = “abccccdd”
Output: 7
Explanation: One longest palindrome that can be built is “dccaccd”, whose length is 7.

Example 2:

Input: s = “a”
Output: 1
Explanation: The longest palindrome that can be built is “a”, whose length is 1.

Constraints:

1 <= s.length <= 2000
s consists of lowercase and/or uppercase English letters only.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(128) = O(1)

409. Longest Palindrome LeetCode Solution in C++

class Solution {
 public:
  int longestPalindrome(string s) {
    int ans = 0;
    vector<int> count(128);

    for (const char c : s)
      ++count[c];

    for (const int freq : count)
      ans += freq % 2 == 0 ? freq : freq - 1;

    const bool hasOddCount =
        ranges::any_of(count, [](int c) { return c % 2 == 1; });
    return ans + hasOddCount;
  }
};
/* code provided by PROGIEZ */

409. Longest Palindrome LeetCode Solution in Java

class Solution {
  public int longestPalindrome(String s) {
    int ans = 0;
    int[] count = new int[128];

    for (final char c : s.toCharArray())
      ++count[c];

    for (final int freq : count)
      ans += freq % 2 == 0 ? freq : freq - 1;

    final boolean hasOddCount = Arrays.stream(count).anyMatch(freq -> freq % 2 == 1);
    return ans + (hasOddCount ? 1 : 0);
  }
}
// code provided by PROGIEZ

409. Longest Palindrome LeetCode Solution in Python

class Solution:
  def longestPalindrome(self, s: str) -> int:
    ans = 0
    count = collections.Counter(s)

    for c in count.values():
      ans += c if c % 2 == 0 else c - 1

    hasOddCount = any(c % 2 == 1 for c in count.values())
    return ans + hasOddCount
# code by PROGIEZ

Additional Resources

See also  337. House Robber III LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.