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 of String INPUT Compressed String: "a3b1a1c2" Parsed segments: a:3 b:1 a:1 c:2 Note: 'a' appears twice! Expanded form: "aaabacc" Input: compressed = "a3b1a1c2" ALGORITHM STEPS 1 Parse String Extract char-freq pairs 2 Build Hash Map Aggregate frequencies HashMap: 'a': 4 'b': 1 'c': 2 a: 3+1=4 3 Sort Keys Alphabetical order: a,b,c 4 Build Result Concat char + count FINAL RESULT Better Compressed String: "a4b1c2" Character breakdown: a count: 4 b count: 1 c count: 2 Verification: [OK] Each char appears once [OK] Alphabetical order [OK] Same total chars: 7 Output: "a4b1c2" Key Insight: Use a HashMap to aggregate character frequencies. Duplicate characters like 'a' appearing multiple times (a:3 and a:1) are merged into a single entry (a:4). Then sort keys alphabetically and rebuild the string. Time: O(n), Space: O(k) where k = unique chars. TutorialsPoint - Better Compression of String | Hash Map Approach
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