Skip to main content
Back to problems
Leetcode
Medium
Strings
Hash Maps
Apply Operations To Make String Empty

Repeatedly remove the most frequent characters from a string until nothing remains.

Acceptance 0%
Problem Statement

Apply Operations To Make String Empty

You are given a string s. In one operation, you may remove all occurrences of the most frequent character currently present in the string.

If there is a tie for the highest frequency, you remove every character whose frequency is tied for the maximum, but only the characters that would be removed in the final operation matter for determining the answer.

Return the string that remains after performing the operation sequence until the string becomes empty. In the common interpretation of this process, the characters that survive the longest are the ones whose last occurrence appears latest in the original string among the characters with maximum frequency.

Goal

Determine which characters are removed in the final round of operations, and return them in their original left-to-right order from the input string.

Input Format

  • A single string s.

The exact platform input format may vary, but the core task is to process one string.

Output Format

  • Return the string formed by the characters that remain after the repeated removal process, in their original order.

For the LeetCode formulation, this is the resulting emptying process outcome as defined by the problem.

Constraints

  • 1 <= |s| <= $10^{5}$
  • s consists of lowercase English letters.
  • A linear or near-linear solution is expected.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "aabcbbca"

Output

"ba"

Explanation

Frequencies are: a=3, b=3, c=2. The characters with maximum frequency are a and b. Their last occurrences are at positions 7 and 5, so the characters that remain in the final outcome are taken in original order from the relevant suffix, giving ba.

Example 2

Input

s = "leetcode"

Output

"code"

Explanation

Each character frequency is either 1 or 2, and the characters that survive the longest are those appearing latest among the most frequent group. The resulting string is the ordered set of characters that remain at the end of the process.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.