← Questions

Sort characters by frequency

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's technical phone screen, last asked Sep 2025. It tests hashing, sorting and bucket sort.

Given a string, rearrange its characters in decreasing order of how often they appear, all copies of each character together. Characters with the same count appear in ascending ASCII order.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • frequency_sort(s: str) -> str

Example

frequency_sort("tree")      ->  "eert"       # e twice; r and t once, r before t
frequency_sort("cccaaa")    ->  "aaaccc"     # a tie, so a before c
frequency_sort("treeA12A")  ->  "AAee12rt"   # A and e twice (A is 65, e is 101); then 1, 2, r, t
frequency_sort("")          ->  ""

Constraints

  • 0 <= len(s) <= 10^5; ASCII characters only (codes 0-127).

Clarifying questions

  • How are ties broken? (Ascending ASCII value, so uppercase before lowercase and digits before letters.)
  • Is the input ASCII only, or Unicode?
  • Is it case-sensitive? (Yes.)

What a strong answer covers

  • Count with an array of 128 (or a hash map), sort the distinct characters by (-count, character), and build the output by repeating each one. O(n + k log k) for k distinct characters, which is O(n) since k <= 128.
  • Bucket sort by count as the alternative: bucket c holds the characters seen c times, read from the highest bucket down.
  • Building the result with a list and a join rather than repeated string concatenation.
  • Tests: empty string, a single character, all characters tied, mixed case and digits.

Follow-ups

  • The string is Unicode text. What changes, and what counts as a character?
  • Stream the output for a very large input that arrives in pieces.

Where it's asked

  • Amazon · Technical phone screen · Last asked Sep 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

hashing · sorting · bucket sort

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