FastPrepSort Characters by Frequency
Problem · String

Sort Characters by Frequency

Learn this problem
MediumSnap Inc. logoSnap Inc.FULLTIMEONSITE INTERVIEW

Problem statement

Given a string s, reorder its characters so characters with higher frequencies appear before characters with lower frequencies.

All copies of the same character must be contiguous. When two characters have the same frequency, place the character with the smaller ASCII code first.

Return the reordered string. Uppercase and lowercase letters are distinct.

Function

frequencySort(s: String) → String

Examples

Example 1

s = "tree"return = "eert"

The character e appears twice. The characters r and t appear once, so ASCII order places r before t.

Example 2

s = "cccaaa"return = "aaaccc"

Both characters appear three times, so the tie is resolved by ASCII order.

Example 3

s = "Aabb"return = "bbAa"

The two lowercase b characters come first. Among the remaining singletons, uppercase A precedes lowercase a by ASCII code.

Constraints

  • 1 <= s.length <= 200000.
  • s contains only uppercase English letters, lowercase English letters, and digits.

More Snap Inc. problems

drafts saved locally
public String frequencySort(String s) {
    // Write your solution here.
}
s"tree"
expected"eert"
checking account