Strings Counting over substrings

140. Sort Characters By Frequency

Medium

You are given a string s. Rearrange its characters so that the characters that appear most often come first, and return the new string. All copies of a character sit next to each other.

Capital and lowercase letters are different characters, so a and A are counted separately.

When two characters appear the same number of times, the one with the smaller ASCII code comes first. So digits come before capital letters, and capital letters come before lowercase letters. This makes the answer unique.

Answers are shown in double quotes.

Example 1

Input: s = "programming"

Output: "ggmmrrainop"

Explanation: g, m and r appear twice each, so they come first, in alphabet order. The five letters that appear once follow, also in alphabet order.

Example 2

Input: s = "aAbBBa1"

Output: "BBaa1Ab"

Explanation: B and a appear twice each, and B comes first because capital letters come before lowercase ones. 1, A and b appear once each.

Example 3

Input: s = "dc2ba1"

Output: "12abcd"

Explanation: Every character appears once, so they all tie. The answer lists them in ASCII order, digits first.

Check your understanding

Work out the answer for this input before you write any code.

s = "banana"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds only English letters, capital and lowercase, and the digits 0 to 9.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.