Educatifu
Open menu

Run-Length Encoding

Mediumstrings

Compress a string by replacing each run of identical consecutive characters with the character followed by the length of the run.

For example, aaabbc becomes a3b2c1.

Input

A single line containing the string s of lower-case English letters.

Output

The run-length encoding of s.

Examples

Example 1

Input
aaabbc
Output
a3b2c1

Three a, two b, one c -> a3b2c1.

Example 2

Input
abcd
Output
a1b1c1d1

No repeats, so every count is 1.

Example 3

Input
zzzzz
Output
z5

A single run of five z.

Constraints

  • 1 <= length of s <= 10^4
  • s consists of lower-case English letters only.

Hints

Reveal hint 1

Scan left to right and group equal characters that sit next to each other.

Reveal hint 2

For each group, output the character once and then how many times it repeated (always include the count, even when it is 1).

Reference solution (spoiler — try it yourself first)

Approach

Walk the string, extending a run while the next character matches. When it changes, emit the character and the run length, then start a new run.

s = input()
res = []
i = 0
while i < len(s):
    j = i
    while j < len(s) and s[j] == s[i]:
        j += 1
    res.append(s[i] + str(j - i))
    i = j
print("".join(res))

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation