Back to Practice
#0110

Run-Length Encode Values

MediumPython25 min20 XP

Problem

Given a list of values, return a list of [value, count] pairs for consecutive runs. Equal values separated later should become separate runs.

Why This Matters

Run-length encoding is a simple way to practice stateful scanning: remember the current value and how long the current run has lasted.

Function Signature

def run_length_encode(items):

Examples

Example 1
Input["a", "a", "b", "a"]
Output[["a", 2], ["b", 1], ["a", 1]]

The final "a" is a new run because it is not consecutive with the first two.

Constraints

  • Return the requested value exactly.
  • Handle the stated edge cases.
  • Keep the solution readable.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input["a", "a", "b", "a"]
Expected[["a", 2], ["b", 1], ["a", 1]]

The final "a" is a new run because it is not consecutive with the first two.

Hidden Test Categories
single itemall same valuesno adjacent repeats