Better Compression of String Problem
#3167
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3167.
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.
Example 1:
Input: compressed = "a3c9b2c1"
Output: "a3b2c10"
Explanation:
Characters "a" and "b" appear only once in the input, but "c" appears twice, once with a size of 9 and once with a size of 1.
Hence, in the resulting string, it should have a size of 10.
Example 2:
Input: compressed = "c2b3a1"
Output: "a1b3c2"
Example 3:
Input: compressed = "a2b4c1"
Output: "a2b4c1"
Constraints:
1 <= compressed.length <= 6 * 10^4compressedconsists only of lowercase English letters and digits.compressedis a valid compression, i.e., each character is followed by its frequency.- Frequencies are in the range
[1, 10^4]and have no leading zeroes.
Solution
Approach: Hash Table + Parsing
Parse the string with two pointers: a letter followed by its digits. Add each number to the total of its letter, then output the letters in alphabetical order with their totals.
Complexity: time O(n + 26 log 26), space O(26).
class Solution:
def betterCompression(self, compressed: str) -> str:
cnt = Counter()
i, n = 0, len(compressed)
while i < n:
j = i + 1
x = 0
while j < n and compressed[j].isdigit():
x = x * 10 + int(compressed[j])
j += 1
cnt[compressed[i]] += x
i = j
return "".join(sorted(f"{k}{v}" for k, v in cnt.items()))