Better Compression of String - Problem

You are given a string compressed representing a compressed version of a string. The format is a character followed by its frequency.

For example, "a3b1a1c2" is a compressed version of the string "aaabacc".

We seek a better compression with the following conditions:

  • Each character should appear only once in the compressed version
  • The characters should be in alphabetical order

Return the better compression of compressed.

Note: In the better version of compression, the order of letters may change, which is acceptable.

Input & Output

Example 1 — Basic Case
$ Input: compressed = "a3b1a1c2"
Output: "a4b1c2"
💡 Note: Character 'a' appears with frequencies 3 and 1, total = 4. Character 'b' appears once with frequency 1. Character 'c' appears once with frequency 2. Result is sorted alphabetically: a4b1c2
Example 2 — Single Character
$ Input: compressed = "c1"
Output: "c1"
💡 Note: Only one character 'c' with frequency 1, so result remains c1
Example 3 — Multiple Duplicates
$ Input: compressed = "a1b1b1a2"
Output: "a3b2"
💡 Note: Character 'a' appears with frequencies 1 and 2, total = 3. Character 'b' appears with frequencies 1 and 1, total = 2. Sorted result: a3b2

Constraints

  • 1 ≤ compressed.length ≤ 1000
  • compressed consists of lowercase English letters and digits
  • Each character in compressed is followed by its frequency
  • 1 ≤ frequency ≤ 999

Visualization

Tap to expand
Better Compression: a3b1a1c2 → a4b1c2Input (scattered)a3b1a1c21. Parse pairs 2. Accumulate frequencies 3. Sort alphabeticallyOutput (consolidated)a4b1c2✓ Each character appears once✓ Alphabetical order maintained✓ Frequencies consolidated (a: 3+1=4)Result: "a4b1c2"
Understanding the Visualization
1
Input
Compressed string with duplicate characters: "a3b1a1c2"
2
Process
Parse pairs, accumulate frequencies, sort alphabetically
3
Output
Better compression with unique characters: "a4b1c2"
Key Takeaway
🎯 Key Insight: Use hash map to accumulate character frequencies, then sort keys alphabetically
Asked in
Google 15 Amazon 12 Microsoft 10 Apple 8
25.6K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen