Longest Palindrome (build from letters) solution explained

This Longest Palindrome problem gives you a bag of letters, written as a string, and asks how long the longest palindrome is that you could build from them, where uppercase and lowercase count as different letters. You never search for anything: every pair of matching letters can sit on opposite sides, and at most one leftover letter can go in the middle. Count each letter, add up the pairs, and add one if any letter has an odd count, for O(n) time.

By Published 7 min read

Which problem this is

Two well-known problems share almost the same name. In this one, the string is just a supply of letters. You may reorder them freely and you do not have to use all of them, and you report the length of the longest palindrome they can make. Letters are case-sensitive, so A and a are different letters. The other problem asks for the longest palindromic substring, a contiguous piece of the original string with its order unchanged, and it is solved by expanding around each center or with dynamic programming. If the prompt mentions rearranging, building or using letters, you are here.

"aabbbcD"    ->  5   for example  abbba     (a a, b b, one b in the middle)
"Zz"         ->  1   Z and z are different letters
"kkkk"       ->  4   kkkk
"xyz"        ->  1   any single letter
"abcabcabc"  ->  7   for example  abcacba   (one pair each, one letter in the middle)
Strings made up for this page, with the best length and one palindrome that reaches it

What the interviewer wants to see

This is a short warm-up, so the bar is a clean argument rather than a clever trick. You should explain the structure of any palindrome (it mirrors around a center, so every letter except possibly the middle one appears an even number of times) and turn that into a counting rule. Interviewers also note whether you ask about case sensitivity and whether you resist reaching for a palindrome-checking loop, which this problem does not need.

A brute force to reason from

A multiset of letters can be arranged into a palindrome exactly when at most one letter appears an odd number of times. So a brute force can try every subset of positions, check that rule, and keep the largest subset that passes. With n letters there are 2ⁿ subsets, so it only works for very short strings, but it makes an honest reference for testing and it puts the key rule on the table early.

from collections import Counter


def longest_palindrome_slow(s):
    best = 0
    for mask in range(1 << len(s)):
        picked = [s[i] for i in range(len(s)) if mask >> i & 1]
        odd = sum(c % 2 for c in Counter(picked).values())
        if odd <= 1:
            best = max(best, len(picked))
    return best
Python: every subset of letters, kept if at most one letter count is odd. Exponential, for tests.

Counting instead of searching

Turn the rule around. To use as many letters as possible, take every letter's count and round it down to an even number; those letters can be split evenly between the two halves. If any letter had an odd count, one of its leftover copies can sit in the middle, which adds exactly one. Only one letter can take the middle, so further odd leftovers are dropped. The answer is the sum of the even parts plus one if anything odd exists, which you can also write as the string length minus the number of odd counts, plus one when that number is positive.

from collections import Counter


def longest_palindrome(s):
    counts = Counter(s)
    length = sum(c // 2 * 2 for c in counts.values())
    if any(c % 2 for c in counts.values()):
        length += 1            # one leftover letter can sit in the middle
    return length
Python: count, keep the even part of each count, add a center if possible
function longestPalindrome(s) {
  const unpaired = new Set();
  let length = 0;
  for (const ch of s) {
    if (unpaired.has(ch)) {
      unpaired.delete(ch);
      length += 2;
    } else {
      unpaired.add(ch);
    }
  }
  return unpaired.size > 0 ? length + 1 : length;
}
JavaScript: a set of unpaired letters; each completed pair adds 2

The set version never builds a count table. Each letter either opens a pair or closes one, so at the end the set holds exactly the letters with an odd count. Both versions make one pass and use space proportional to the number of distinct letters, which is at most 52 for English letters in two cases.

Building the palindrome too

A common follow-up asks for an actual palindrome of that length. Write half of each letter's pairs into a left half, pick any letter with an odd count for the middle, and mirror the left half to finish. Sorting the letters first makes the result predictable, and it also gives the smallest possible left half in character-code order, where uppercase letters come before lowercase ones.

from collections import Counter


def build_palindrome(s):
    counts = Counter(s)
    half = "".join(ch * (counts[ch] // 2) for ch in sorted(counts))
    middle = next((ch for ch in sorted(counts) if counts[ch] % 2), "")
    return half + middle + half[::-1]
Python: construct one longest palindrome from the counts

Complexity

n letters, d distinct letters
ApproachTimeExtra space
Try every subsetO(2ⁿ · n)O(n)
Count tableO(n)O(d), constant for a fixed alphabet
Set of unpaired lettersO(n)O(d)
Build one palindromeO(n + d log d)O(n) for the output
n letters, d distinct letters. Scroll sideways on a small screen.

Inputs to try

  • An empty string: 0.
  • One letter: 1.
  • All copies of one letter: the full length, odd or even.
  • All letters distinct: 1.
  • Upper and lower case of the same letter, such as "Zz": 1, not 2.
  • Several letters with odd counts, such as "aaabbbccc": 7, using one middle letter only.

Ways to get it wrong

  • Adding 1 for every letter with an odd count instead of once in total.
  • Skipping letters with odd counts entirely, which loses their even part (three b's still give a pair).
  • Lowercasing the input when the problem treats cases as different.
  • Solving the longest palindromic substring problem instead, because the name sounds the same.
  • Building every permutation and checking each one, which is factorial time for a counting question.

Neighbors of this problem

  • Can the whole string be rearranged into a palindrome? Yes exactly when at most one letter has an odd count.
  • Longest palindrome from two-letter words: pair each word with its reverse, and allow at most one word whose two letters match to sit in the middle.
  • Longest palindromic subsequence: order is kept but letters may be skipped, which needs dynamic programming.
  • Longest palindromic substring: order is kept and letters must be contiguous; expand around each center.

Explaining it in the interview

Fictional example

Getting from the definition to the formula
Candidate
Before I code, is this case-sensitive, and can I rearrange the letters? Okay, yes and yes.
Candidate
A palindrome mirrors around its center, so every letter appears an even number of times except possibly the one in the middle.
Candidate
So I count each letter and keep the even part of every count. If any count was odd, one leftover letter can go in the middle, so I add one.
Interviewer
What if three different letters have odd counts?
Candidate
Each still gives its pairs, but only one leftover fits in the middle, so I add one in total, not three.

Counting with a map is the same tool that powers Two Sum and Top K Frequent Elements. Within this set, Fruit Into Baskets and Max Consecutive Ones III also count as they go, but inside a moving window. For a stack-based contrast, try Asteroid Collision.

Natively for warm-up questions

Short problems like this one are where a confident, two-sentence explanation matters most, because the interviewer moves on quickly. On Mac or Windows, Natively can read the prompt from a screenshot during practice, flag whether it is the counting problem or the substring one, and transcribe your explanation so you can tighten it. See what the interview assistant does.

Questions people ask

How do you solve Longest Palindrome?

Count each letter. Add every count rounded down to an even number, then add 1 if any letter had an odd count, since one leftover letter can sit in the middle.

Is Longest Palindrome the same as longest palindromic substring?

No. Here you may rearrange letters and leave some out, so it is a counting problem. The substring problem keeps the original order and contiguity and is solved by expanding around centers.

What is the time complexity of Longest Palindrome?

O(n) for one pass over the string. Extra space depends on the number of distinct letters, which is constant for a fixed alphabet.

Why add only one for odd counts?

A palindrome has a single center, so only one letter can appear an odd number of times. Other letters with odd counts still contribute their pairs, but their last copy is left out.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP