Algorithmscharacter repetition

Character Repetition Patterns (Run-Length Thinking)

TT
Testlaa Team
May 14, 20261 min read

Repetition patterns detect runs like aaa or 1111—compress them (run-length encoding), validate passwords (“no three repeats”), or parse tokens.

Why this shows up in the real world

Barcode widths encode long runs of narrow vs wide bars. Compression (fax, TIFF) exploits repeated characters heavily.

Core idea (explained for students)

Single pass: keep count and prev; on change emit (prev, count) and reset. Edge case: flush the final run after the loop.

Try this in Python

def run_length_encode(s: str) -> list[tuple[str, int]]:
    if not s:
        return []
    out, prev, cnt = [], s[0], 1
    for ch in s[1:]:
        if ch == prev:
            cnt += 1
        else:
            out.append((prev, cnt))
            prev, cnt = ch, 1
    out.append((prev, cnt))
    return out


print(run_length_encode("aaabba"))

Common mistakes

  • Empty string—no runs to emit.
  • Counting length-one runs incorrectly at string end.

Key takeaways

  • Run-length thinking underpins string compression interview questions.
  • Always test s with length 1 and all identical chars.

Tags:

StringsPythonStudents