Smallest palindrome from a symmetric string's letters
I was asked this
No reports yet. Sign in to say where you were asked it.
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-
scontains 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
atozpossible? - 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 // 2times in alphabetical order, then returnsleft + 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
