623. Compressing Runs of Letters
Replace each MAXIMAL run of identical letters by that letter followed by the run's length. A run of length 1 keeps just the letter, with no number after it.
Print the compressed string. It is printed even when it is longer than the original.
aaabbc -> a3b2c
abc -> abc every run has length 1
zzzz... -> z12 twelve z characters
## Two pointers walking the runs
One pointer marks where the current run STARTS, the other walks to its end:
i = 0
while i < n:
j = i
while j < n and s[j] == s[i]: j += 1
emit s[i], and j-i only if j-i > 1
i = j
j never goes back, and i jumps straight to j, so each character is examined once and the
whole pass is linear.
The alternative, a single pointer with a running counter, is equally correct. The two-pointer form is written here because the run BOUNDARIES are explicit, which is what you need the moment the problem asks for the runs themselves rather than a summary of them.
## Where the off-by-one lives
The run is s[i .. j-1], so its length is j - i, not j - i + 1. The character at j is the
one that ENDED the run and belongs to the next one.
Getting this wrong adds one to every count and is invisible on a string of single characters,
which is exactly why abc is a poor test for it and aaabbc is a good one.
## Lengths above nine
A run of twelve writes z12, two characters of digits. The output is not one character per
run, and code that assumes a fixed width per run breaks on the first run of ten.
## It may grow
abc compresses to abc, the same length. Nothing shorter is required, and a version that
returns the original when the compressed form is longer is answering a different question. The
statement says the compressed form is always printed.
## Boundaries
A single character prints itself. A string of one repeated character prints one letter and one number.
## Cost
Time O(n). Space O(n) for the output.
Constraints - `1 ≤ length ≤ 200000` - the string contains only lowercase letters
Input
One line containing a non-empty string of lowercase letters.
Output
Print the compressed string on one line.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.