easy +10 pts

Compress Bits Run

Turn long runs of identical bits into compact pairs.

Write a function `compress_bits_run(bits: str) -> str` that takes a non-empty string of '0' and '1' characters and compresses it. For each maximal consecutive run of the same bit, output the length of the run (in decimal) followed by the bit. For example, `'111000'` becomes `'31 30'` (3 ones, then 3 zeros). Runs are processed left to right. The input will contain only '0' and '1'. The output should be a string with each pair separated by a single space. There must be no trailing space.

Constraints

1 <= len(bits) <= 10000. Input consists only of characters '0' and '1'. Time complexity O(n), space O(n) for output.

Example

>>> compress_bits_run('111000')
'31 30'
>>> compress_bits_run('0')
'10'
>>> compress_bits_run('101')
'11 10 11'
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate through the string and count how many times the same character appears consecutively.
When the character changes, append the count and the character to a list, then reset the counter.
Join the list with a space to produce the output string.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.