409. Longest Palindrome

Solution

/**
 * @param {string} s
 * @return {number}
 */
 var longestPalindrome = function(s) {
    if (s.length === 1) {
        return 1;
    }
    
    const l = {};
    
    for (const c of s) {
        if (l[c]) {
            l[c]++;
        } else {
            l[c] = 1;
        }
    }

    let total = 0;
    let foundEven = false;

    for (let char of Object.keys(l)) {
        let count = l[char];
        if (count % 2 === 0) {
            total += count;
        }  else {
            foundEven = true;
            total += count - 1;
        }
    }

    if (foundEven) {
        total++;
    }
    
    return total;
};

Complexity

  • Time Complexity: O(N), where N is the size of s.
  • Space Complexity: O(1), as the alphabet size of l is fixed.

All Solutions