Dataford
Interview Guides
Upgrade
All questions/Coding/Sort Characters by Frequency

Sort Characters by Frequency

Easy
Coding
Asked at 1 company1ArraysStringsHash Tables
Also asked at
Booking

Problem

Given a string s, return a new string where characters are grouped and ordered by decreasing frequency. If two characters have the same frequency, any relative order between them is valid.

Examples

Example 1
Inputs = "tree"Output"eert"Why`e` appears twice, so it must come before characters that appear once.
Example 2
Inputs = "cccaaa"Output"cccaaa"Why`c` and `a` both appear three times, so either grouped order is acceptable.

Constraints

  • `1 <= len(s) <= 5 * 10^5`
  • `s` may contain letters, digits, and symbols
  • Equal frequencies may appear in any order

Problem

Given a string s, return a new string where characters are grouped and ordered by decreasing frequency. If two characters have the same frequency, any relative order between them is valid.

Examples

Example 1
Inputs = "tree"Output"eert"Why`e` appears twice, so it must come before characters that appear once.
Example 2
Inputs = "cccaaa"Output"cccaaa"Why`c` and `a` both appear three times, so either grouped order is acceptable.

Constraints

  • `1 <= len(s) <= 5 * 10^5`
  • `s` may contain letters, digits, and symbols
  • Equal frequencies may appear in any order
Practice Python
Python 3.10
Open on desktop for the full Python editor with syntax highlighting and autocomplete.