PPractick

DSA interview question

Sort Characters by Frequency

Easy · Algorithms · Topics: string, hash map, sorting

The problem

A text-analytics widget displays a word with its most frequent characters first: "tree" becomes "eert", because 'e' appears twice and the other letters once. Every copy of a character stays together. The natural approach counts each character, then orders characters by count, most frequent first. For a deterministic display, characters with equal counts appear in increasing character order. A bucket sort by frequency brings it down to linear time.

Example: "tree" → "eert"; "cccaaa" → "aaaccc".

Function signature

string frequencySort(const string& s);  // higher frequency first; ties by character code, ascending

Test cases

Input sOutputExplanation
"tree""eert"e×2, then r and t (r < t)
"cccaaa""aaaccc"Tie at 3: 'a' comes before 'c'
"Aabb""bbAa"b×2, then 'A' (65) before 'a' (97)
"z""z"
""""

(Confirm: characters are ASCII; case-sensitive; LeetCode accepts any order among ties, while this version fixes it for determinism.)

How interviewers phrase it

Clarifying questions to ask

  1. How should ties be ordered?
  2. Case-sensitive? Which character set?
  3. Should equal characters be grouped together? (Yes.)

Follow-ups to expect

  1. "How do you order by frequency efficiently?"
  2. "Why is bucket sort linear?"
  3. "How would you do it with a heap?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in