Summarize consecutive character runs

Problem

Implement summarize_runs(text), which returns (character, count) for each maximal consecutive run. For example, "aaabbcaa" becomes [("a", 3), ("b", 2), ("c", 1), ("a", 2)]. Return an empty list for an empty string.

Reveal answer or reference solution

Keep the current character and count. When the next character differs, emit the completed run and reset the state. Emit the final run after the loop. The algorithm takes O(n)O(n) time, O(1)O(1) auxiliary space, and O(r)O(r) output space for rr runs.

def summarize_runs(text: str) -> list[tuple[str, int]]:
    if text == "":
        return []
    runs: list[tuple[str, int]] = []
    current = text[0]
    count = 1
    for index in range(1, len(text)):
        character = text[index]
        if character == current:
            count += 1
        else:
            runs.append((current, count))
            current = character
            count = 1
    runs.append((current, count))
    return runs

Public tests

  • summarize_runs("") → []
  • summarize_runs("z") → [('z', 1)]
  • summarize_runs("aaabbcaa") → [('a', 3), ('b', 2), ('c', 1), ('a', 2)]
  • summarize_runs("ab") → [('a', 1), ('b', 1)]
Outcome

Previous attempts

Loading attempts saved in this browser…

    Review Screening Results