JavaMediumStrings20 min
Compress consecutive character runs
Replace each maximal run by its character followed by its decimal count, including runs of length one. Follow the stated ordering and edge-case conventions exactly. Interviewers use this task to probe boundary handling and collection selection.
Input
One line of lowercase English letters, possibly empty.
Output
Replace each maximal run by its character followed by its decimal count, including runs of length one.
Constraints
0 <= length <= 100000.
Example
Input
aabccc
Output
a2b1c3
Example 2 input
aabba
Output
a2b2a1
This example exercises a further boundary or ordering case.
Public test cases (2)
Input
aabccc
Expected output
a2b1c3
Input
abcd
Expected output
a1b1c1d1
Hints (2)
- Identify the state needed to avoid recomputing work for each element.
- Walk to the end of each maximal run and emit its length once.
Target complexity: time O(n) · space O(n)
