← Questions

Longest palindrome from equal-length words

0

A coding interview question asked at Microsoft and Meta. It tests hash map, strings and greedy.

You are given a list of words. Every word has the same length k and uses lowercase letters. The list can contain duplicates.

Pick some of the words (possibly none) and join them in any order to form a palindrome. Each entry in the list can be used at most once, so a word can appear as many times as it occurs in the list, and no more.

Implement:

def longest_palindrome_length(words: list[str]) -> int: ...
def build_longest_palindrome(words: list[str]) -> str: ...
  • longest_palindrome_length returns the length of the longest palindrome you can build, or 0 if you cannot build one.
  • build_longest_palindrome returns one such palindrome, or "".

Constraints

  • 0 <= len(words) <= 10^5
  • 1 <= k <= 10, and all words have length k

Example 1

words = ["ab", "ba", "cc", "cc", "cc"]
longest_palindrome_length(words) -> 10
build_longest_palindrome(words)  -> "abccccccba"

"ab" and "ba" mirror each other, two "cc" form another mirror pair, and the third "cc" goes in the middle.

Example 2

words = ["abc", "cba", "bab", "xyx"]
longest_palindrome_length(words) -> 9

For example "abcbabcba". Only one of "bab" and "xyx" can be in the middle.

Clarifying questions

  • Should an empty list, or a list with no usable words, return 0 and ""?
  • When several palindromes have the longest length, is any of them fine for build_longest_palindrome?
  • Does k = 1 work the same way (every single letter is a palindrome on its own)?
  • Is the length counted in characters, so a palindrome of w words has length w * k?

What a strong answer covers

  • Counts words in a hash map. For a word that is not its own reverse, pairs it with its reverse and uses min(count[w], count[reverse(w)]) pairs. For a word that is its own reverse, uses count // 2 pairs.
  • Puts one leftover self-palindromic word in the middle if any word has an odd count, and only one.
  • Builds the string by laying out the left halves, the middle word, then the left halves reversed in reverse order, so the result is a palindrome by construction.
  • Counts each pair once (not once for ab and again for ba). O(n * k) time and O(n * k) space.
  • Tests: both examples, no pairs and no middle (length 0), several self-palindromic words with odd counts, duplicates of a word whose reverse appears once, and a check that the built string is a palindrome of the reported length.

Follow-ups

  • Words have different lengths.
  • Return the lexicographically smallest longest palindrome.
  • Count how many distinct longest palindromes can be built.
  • Words arrive one at a time: keep the answer up to date.

Where it's asked

What it tests

hash map · strings · greedy · palindrome

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding