📖 2 min read
Last updated on

Longest Palindrome — Coding Interview Walkthrough


Longest Palindrome asks for the length of the longest palindrome you can build from a set of characters. Don’t confuse it with Longest Palindromic Substring — this one is about construction, not search. It tests whether you understand palindrome structure and can derive a greedy rule from first principles.


The Problem

Given a string s, return the length of the longest palindrome that can be built with its characters. Letters are case-sensitive.

Example

Input: s = "abccccdd" Output: 7 — one longest palindrome is "dccaccd" (2 d’s, 4 c’s, 1 a).

Already comfortable with the solution? Practice it in a mock interview →

String 'abccccdd' with paired characters (c×4, d×2) highlighted in teal. Pairs form the palindrome body, one unpaired char goes in the center.

What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
Palindrome structureDo you know palindromes are built from pairs + at most one center?
Greedy reasoningCan you derive the rule from first principles?
Case sensitivityDo you treat ‘A’ and ‘a’ as different?

Step 1: Clarifying Questions

  1. Case-sensitive? Yes — 'A' and 'a' are different.
  2. Can we reorder characters? Yes — we’re building, not finding in-place.

Step 2: The Key Insight

A palindrome is made of pairs plus at most one center character. Each character with an even frequency contributes its full count. Each odd-frequency character contributes count - 1. If any character has an odd frequency, add 1 for the center.


Python Implementation

from collections import Counter

def longestPalindrome(s: str) -> int:
    freq = Counter(s)
    length = 0
    has_odd = False

    for count in freq.values():
        length += count // 2 * 2
        if count % 2 == 1:
            has_odd = True

    return length + (1 if has_odd else 0)

Time & Space Complexity

AspectComplexity
TimeO(n)
SpaceO(k) — k unique characters

Common Interview Mistakes

  1. Confusing with Longest Palindromic Substring. This builds a palindrome from characters; that finds one within a string.
  2. Forgetting case sensitivity. 'A' and 'a' are separate entries.
  3. Not adding the center +1. Forgetting the optional center gives length - 1.

What a Strong Candidate Sounds Like

“A palindrome consists of pairs plus an optional center. For each character, I use count // 2 * 2 — the even portion. If any character had an odd count, I place one in the center. The answer is the sum of all even portions plus 1 if any odd count exists.”



Practice This in a Mock Interview

Start a mock interview for Longest Palindrome on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →