Run-Length Label
EasyArrays & Hashing
Problem
A label printer saves ink by compressing text: each maximal run of the same letter is written as the letter followed by the run length, except that runs of length 1 are written as just the letter.
Given text made of lowercase letters, return its compressed form. For example "aaabcc" becomes "a3bc2".
Example 1
- Input:
- text = "aaabcc"
- Output:
- "a3bc2"
Runs: aaa → a3, b → b, cc → c2.
Example 2
- Input:
- text = "abc"
- Output:
- "abc"
Every run has length 1.
Example 3
- Input:
- text = "zzzzzzzzzzzz"
- Output:
- "z12"
Run lengths can have several digits.
Constraints
- 0 ≤ text.length ≤ 10^5
- text contains only lowercase English letters.
Hint
Show the first hint
Process the text one run at a time rather than one character at a time.
Walkthrough
How to approach it
01Clarify before coding
- Are runs that reappear later merged? No, 'aabbaa' has three runs: a2b2a2.
- How is a run of length 1 written? Just the letter, no '1'.
- Can the text be empty? Yes, return an empty string.
02Brute force
For each position, count how many equal letters follow it, append the piece, and skip ahead; concatenating strings with += in a loop.
Cost: The counting is linear, but naive repeated string concatenation can be O(n²) in languages with immutable strings.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.