Everything That Repeats

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Meta

Problem

A storage layer holds long status strings where the same character tends to repeat in stretches, and we want a compact form of s. Replace each stretch of one repeated character with that character followed by how many times it repeats in a row, and always write the count even when a character shows up just once.

Say it once, then say how many times it stayed.

Example 1

Input:

s = "aaabbc"

Output:

"a3b2c1"

Example 2

Input:

s = "aabbaa"

Output:

"a2b2a2"

Worked solution and explanation

What this really is

Strip the storage-compression costume and this is a single left-to-right scan that has to remember one thing: the character it is currently inside a run of, and how long that run has gotten. The whole problem lives in the transitions. Anyone can count; what separates candidates is handling the two moments where a run ENDS: when the next character differs, and when the string simply runs out. Miss the second one and your last group silently vanishes.


The trap that bites


Break down the requirements

Step 1: Initialize tracking variables

Anchor on the first character with a count of 1. These two variables ARE the current run as you scan.

Step 2: Compare each character to its neighbor

From the second character on, compare to the previous one: same character means bump the count, a different one means the run just ended, so flush 'char + count' and reset count to 1.

Step 3: Flush the final run after the loop

The final run never meets a differing character to trigger its flush, so the loop alone leaves it unwritten. Append it explicitly after the loop. This is the single most-missed line.


The solution

Single-pass run-length encoding
def run_length_encode(s: str) -> str:
    if not s:
        return ""
    result = ""
    count = 1
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            count += 1
        else:
            result += s[i - 1] + str(count)
            count = 1
    result += s[-1] + str(count)
    return result

Common follow-up questions