</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Custom Comparators

What is this?

Sometimes "smallest to largest" isn't the order you want. A comparator is a little rule you hand the sort that, for any two items, says which one comes first. With the right rule you can order by frequency, by a made-up alphabet, or by which pairing forms the biggest number โ€” and the sort handles the rest.

flowchart TD A["Custom Comparators"] --> B["Pick a pairwise rule"] B --> C["Transformed key like frequency"] B --> D["Direct compare like a plus b"] C --> E["Sort runs the rest"] D --> E

๐Ÿ’ก Fun fact: Telling a sort what to compare instead of writing the sort yourself is why one well-chosen comparator can turn a hard interview problem into a single line of code.

๐Ÿ”“ The 4 problems in this chapter are free. Sign in with Google or Microsoft to start solving.


Core idea: Sorting isn't only "smallest to largest." When the right order is some other rule โ€” biggest concatenation, highest frequency, a made-up alphabet โ€” you hand the sort a custom comparator (or a custom key) that says, for any two items, which comes first. Get that pairwise rule right and the library sort does the rest in O(n log n).


The pattern

A comparator answers one question: given items a and b, which goes first? The trick is choosing the comparison that makes the global arrangement come out right. Sometimes the key is a transformed value (frequency, then value as a tie-break). Sometimes it's a direct pairwise test โ€” comparing a+b against b+a instead of the numbers themselves. When the ordering is by count, you often skip the comparator entirely and bucket by count, reading buckets back in the order you want. And to verify an order rather than produce one, replace each element by its rank in the target order and check the sequence is non-decreasing.


The problems

Custom comparators branch into four problems: Largest Number (compare a+b vs b+a), Sort Array by Increasing Frequency (frequency then value), Sort Characters By Frequency (bucket by count), Verifying an Alien Dictionary (rank-map order check)

  • Largest Number โ€” sort the numbers as strings with the pairwise rule "a before b if a+b > b+a"; concatenate the result. The clever comparator sidesteps a tricky greedy argument.
  • Sort Array by Increasing Frequency โ€” count occurrences, then sort by frequency ascending, breaking ties by value descending. A two-key comparator.
  • Sort Characters By Frequency โ€” tally each character, then bucket by count and emit characters from high-count buckets to low; build the output string.
  • Verifying an Alien Dictionary โ€” build a rank map from the alien alphabet, then check each adjacent word pair is in order under that ranking (with the prefix edge case).

Key takeaways

  • A comparator is just a pairwise "who's first?" rule โ€” pick the one that makes the whole order correct.
  • Multi-key sorting chains tie-breakers (frequency, then value) into one comparator.
  • Bucket by count when the order is purely by frequency โ€” often beating a comparator outright.
  • To verify an order, map to ranks and check the sequence is monotonic.
  • Why it matters: real data rarely sorts by its raw value โ€” custom orderings are the everyday tool.

Order: Largest Number โ†’ Sort Array by Increasing Frequency โ†’ Sort Characters By Frequency โ†’ Verifying an Alien Dictionary.

Core idea: First count how often each character appears, then order the characters by that count, highest first, and emit each character repeated count times. The reordering isn't about the characters themselves โ€” it's about their tallies. Once you have the counts, the rest is just "biggest pile goes first."

Problem, rephrased

You run a sentiment dashboard and want to render a word as a "weighted glyph cloud": the letters that occur most often should appear first so they read as visually dominant. Given the raw string, produce a new string where characters are grouped together and ordered by decreasing frequency. Characters with the same count can come in any order, but each character's copies must be contiguous โ€” you can't sprinkle them.

Formally (LeetCode 451): given a string s, return it sorted in decreasing order of character frequency. If multiple orderings are valid, return any of them.

Input A valid output Note
"tree" "eert" eร—2 leads; r and t tie at 1, either order is fine
"tree" "eetr" also valid โ€” ties are free to reorder
"cccaaa" "aaaccc" both at 3; "cccaaa" equally valid โ€” but never "cacaca"
"Aabb" "bbAa" case-sensitive: A and a are different characters

Output is the same multiset of characters as the input, just regrouped and reordered so the heaviest counts come first. Nothing added, nothing dropped.

Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.