Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-031

Run-Length Encoding

Problem

Encode a string by replacing each maximal run of identical characters with the character followed by the run length.

For example aaabbc encodes to a3b2c1 and a single character encodes to a1. Return the empty string for empty input.

Hint

Track a run counter and flush it whenever the character changes, including at the end.

Test cases

case 1
in: ["aaabbc"]
expected: "a3b2c1"
case 2
in: [""]
expected: ""
case 3
in: ["a"]
expected: "a1"
case 4
in: ["abcd"]
expected: "a1b1c1d1"
case 5
in: ["aabbaa"]
expected: "a2b2a2"
Starter codePython
def run_length_encode(s):
    # Your code here
    pass

5 test cases · run your code against them in the editor