Longest Palindrome From A String

Longest Palindrome From A String

LeetCode 409

What is Palindrome?

A palindrome is a string or a number that is read the same backward or forward.

Ex: 101, 1331, 11, PEEP, ROTATOR, etc are some examples of a palindrome

Note - One can make a string palindrome by pasting the reversed version of the original string at the end of the string

Ex: Code is not a palindrome but Codeedoc is a palindrome.

Input Format

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 here.

Example 1:
Input: string = "abccccddeee"
Output: 9

Solution

const longestPalindrome = (string) => {

    /* Javascript Object to store the key value pair */
    const map = {}

    let ans = 0, firstOdd = false

    /* Setup Map for the given string */

    for (let val of string) {
        map[val] = map[val] ? map[val] + 1 : 1
    }

    /* Logic for fetching length */

    for (let key in map) { /* Iterating over map to get each key*/
        if (map[key] % 2 === 0) {
            ans += map[key]
        } else {
            if (!firstOdd) {
                ans += map[key]
                firstOdd = true
            } else {
                ans += map[key] - 1
            }
        }
    }

    /* returning the length of longest palindrom */
    return ans
};

Reference

It is a leet code problem number 409 and it is considered as one of the easiest problem.

Did you find this article valuable?

Support Sandeep Rana by becoming a sponsor. Any amount is appreciated!