Run-length string compression
Walk the string counting runs of equal characters and append each char + count to a list, joined at the end. Building with += makes it O(n²) — which is half of why this question is asked. Return the original unless the compressed form is genuinely shorter.
Overview
The algorithm, and the trap inside it
Two pointers: one at the start of the current run, one scanning forward while the character stays the same. When it changes, emit char and count and move on. One pass, O(n).
The trap is what you emit into. result += ch + str(n) allocates a new string on every run, which makes the whole thing quadratic in the output length. Appending to a list and joining once is O(n). Interviewers ask this question partly to see which you reach for.
Step through it
What to watch
- Each highlighted block is one run, consumed in a single step.
- The output grows by two characters per run, not per input character.
- The final check is the part most people forget.
Say this out loud
"Count runs, append to a list, join at the end - never += in the loop. And return the original if compression didn't help, which 'abc' doesn't."