KatInterview

409. Longest Palindrome

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the longest palindrome that can be constructed from a given string of lowercase or uppercase English letters. A key aspect is that the letters are case-sensitive. The core idea behind forming a palindrome is using pairs of identical characters. For example, "racecar" is formed by pairs r-r, a-a, c-c, and a single central character e.

Solution

Longest Palindrome in Python

import collections

class Solution:
    def longestPalindrome(self, s: str) -> int:
        # Count frequencies of each character.
        counts = collections.Counter(s)
        
        length = 0
        # Iterate through the frequency of each character.
        for count in counts.values():
            # For each character, we can use an even number of occurrences
            # to form pairs in the palindrome.
            # (count // 2) * 2 gives the largest even number <= count.
            length += (count // 2) * 2
        
        # If the total length from pairs is less than the original string length,
        # it means there was at least one character with an odd count.
        # We can place one of these unique characters in the center of the palindrome.
        if length < len(s):
            length += 1
            
        return length

Longest Palindrome in Java

class Solution {
    public int longestPalindrome(String s) {
        // Frequency array for ASCII characters. 'z' is 122, so 128 is sufficient.
        int[] counts = new int[128];
        
        // Count frequencies of each character in the string.
        for (char c : s.toCharArray()) {
            counts[c]++;
        }
        
        int length = 0;
        // Iterate through the frequency counts.
        for (int count : counts) {
            // For each character, we can use an even number of occurrences
            // to form pairs in the palindrome.
            // (count / 2) * 2 gives the largest even number <= count.
            length += (count / 2) * 2;
        }
        
        // If the total length from pairs is less than the original string length,
        // it means there was at least one character with an odd count.
        // We can place one of these unique characters in the center of the palindrome.
        if (length < s.length()) {
            length++;
        }
        
        return length;
    }
}

Longest Palindrome in C++

class Solution {
public:
    int longestPalindrome(string s) {
        // Frequency array for ASCII characters. 'z' is 122, so 128 is sufficient.
        int counts[128] = {0};
        
        // Count frequencies of each character in the string.
        for (char c : s) {
            counts[c]++;
        }
        
        int length = 0;
        // Iterate through the frequency counts.
        for (int count : counts) {
            // For each character, we can use an even number of occurrences
            // to form pairs in the palindrome.
            // (count / 2) * 2 gives the largest even number <= count.
            length += (count / 2) * 2;
        }
        
        // If the total length from pairs is less than the original string length,
        // it means there was at least one character with an odd count.
        // We can place one of these unique characters in the center of the palindrome.
        if (length < s.length()) {
            length++;
        }
        
        return length;
    }
};

Longest Palindrome in TypeScript

function longestPalindrome(s: string): number {
    // Frequency array for ASCII characters. 'z' is 122, so 128 is sufficient.
    const counts = new Array(128).fill(0);

    // Count frequencies of each character in the string.
    for (let i = 0; i < s.length; i++) {
        counts[s.charCodeAt(i)]++;
    }

    let length = 0;
    // Iterate through the frequency counts.
    for (const count of counts) {
        // For each character, we can use an even number of occurrences
        // to form pairs in the palindrome.
        // Math.floor(count / 2) * 2 gives the largest even number <= count.
        length += Math.floor(count / 2) * 2;
    }

    // If the total length from pairs is less than the original string length,
    // it means there was at least one character with an odd count.
    // We can place one of these unique characters in the center of the palindrome.
    if (length < s.length) {
        length++;
    }

    return length;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.