Run-Length Encode a String

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.5
Write run_length_encode(s) that compresses s by replacing every run of identical consecutive characters with the character followed by its run length, e.g. "aaabbc" becomes "a3b2c1". Every character gets a count, even runs of length 1.

Examples

Example 1
Input
s = 'aaabbc'
Output
'a3b2c1'
Explanation

'aaa' -> a3, 'bb' -> b2, 'c' -> c1.

Example 2
Input
s = 'abc'
Output
'a1b1c1'
Explanation

Every character is its own run of length 1.

Constraints

  • 0 <= len(s) <= 10^4

Topics

StringsString Compression

Companies

AmazonAdobe

Hints

Hint 1

Walk the string tracking a running count; when the next character differs from the current one, flush char+count to the result.

Hint 2

Don't forget to flush the final run after the loop ends.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.