← Questions

Smallest palindrome from a symmetric string's letters

0
AmazonCoding

A coding interview question asked at Amazon. It tests strings, counting and greedy.

You are given a string s of lowercase English letters that is already a palindrome. Rearrange all of its characters to form a new palindrome, and return the one that comes first in dictionary (lexicographic) order.

Implement:

def smallest_palindrome(s: str) -> str: ...

If the input turns out not to allow any palindrome, return the empty string.

Constraints

  • 1 <= len(s) <= 10^5
  • s contains only 'a' to 'z'.

Example 1

Input:  s = "cbabc"
Output: "bcacb"

The letters are two b, two c and one a. The a must sit in the middle, and putting b before c on the left gives the smallest result.

Example 2

Input:  s = "daccad"
Output: "acddca"

Every letter appears an even number of times, so there is no middle character.

Clarifying questions

  • Is the input always a palindrome, or should the code check the letter counts anyway?
  • Is the output allowed to equal the input when the input is already the smallest?
  • Are only lowercase a to z possible?
  • What should be returned when no palindrome is possible: the empty string?

What a strong answer covers

  • Counts the letters; at most one letter may have an odd count, and that letter's extra copy goes in the middle.
  • Builds the left half by taking each letter count // 2 times in alphabetical order, then returns left + middle + reversed(left).
  • O(n) time with a 26-entry count array, no sorting of the full string.
  • Tests both examples, a single letter, all the same letter, and a string with two odd counts.

Follow-ups

  • Return the next larger palindrome made from the same letters.
  • The input is any string, not a palindrome: return the smallest palindrome from its letters, or "".
  • Return the k-th smallest palindrome from the letters.

Where it's asked

What it tests

strings · counting · 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