Better Compression of String - Problem
Better String Compression Challenge
You're given a compressed string where each character is followed by its frequency count. Your task is to create an optimized compression that follows these rules:
๐ฏ Optimization Rules:
โข Each character appears only once in the result
โข Characters are arranged in alphabetical order
โข Combine frequencies for duplicate characters
Example:
The better compression would be
Note: The order of characters may change in the optimized version, which is perfectly acceptable.
You're given a compressed string where each character is followed by its frequency count. Your task is to create an optimized compression that follows these rules:
๐ฏ Optimization Rules:
โข Each character appears only once in the result
โข Characters are arranged in alphabetical order
โข Combine frequencies for duplicate characters
Example:
"a3b1a1c2" represents the string "aaabacc"The better compression would be
"a4b1c2" (combining both 'a' occurrences: 3+1=4)Note: The order of characters may change in the optimized version, which is perfectly acceptable.
Input & Output
example_1.py โ Basic Compression
$
Input:
"a3b1a1c2"
โบ
Output:
"a4b1c2"
๐ก Note:
The character 'a' appears twice with frequencies 3 and 1, so we combine them to get 4. Characters are sorted alphabetically: a(4), b(1), c(2).
example_2.py โ Multiple Duplicates
$
Input:
"z1a3b2z2a1"
โบ
Output:
"a4b2z3"
๐ก Note:
Character 'a' appears with frequencies 3+1=4, 'z' appears with frequencies 1+2=3. Final sorted order: a(4), b(2), z(3).
example_3.py โ Single Characters
$
Input:
"x1y1z1"
โบ
Output:
"x1y1z1"
๐ก Note:
No duplicate characters to combine, already in alphabetical order, so result remains the same.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Hash Table
Create empty frequency counter for each character
2
Parse & Update
For each character-frequency pair, update hash table in O(1) time
3
Combine Duplicates
Hash table automatically handles duplicate characters by updating counts
4
Sort & Output
Extract all characters, sort alphabetically, and build final compressed string
Key Takeaway
๐ฏ Key Insight: Hash tables transform an O(nยฒ) character search problem into an O(n) frequency counting solution by providing instant lookups and updates, making the overall algorithm optimal for string compression tasks.
Time & Space Complexity
Time Complexity
O(n + k log k)
O(n) to parse string + O(k log k) to sort k unique characters
โก Linearithmic
Space Complexity
O(k)
Hash map stores at most k unique characters
โ Linear Space
Constraints
- 1 โค compressed.length โค 1000
- compressed consists of lowercase English letters and digits
- Each character is followed by its frequency (1 โค frequency โค 104)
- The compressed string is guaranteed to be valid
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code