🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.
Run-length encoding shortens a stretch of the same repeated character into "the
character plus a count". Implement compress(s), which compresses a string this
way.
A single arbitrary string.
s = "aaabbccccdaa"
Digits and spaces may appear alongside letters. None of them get special treatment — each is just a character.
Return the compressed string.
compress("aaabbccccdaa")
# "a3b2c4d1a2"
Splitting the input into runs from the left:
aaa: a repeated three times → a3bb: b repeated twice → b2cccc: c repeated four times → c4d: d appeared once → d1aa: a repeated twice again → a2Concatenated, that is "a3b2c4d1a2".
A run is a stretch of the same character in a row. Separated occurrences of the same character are not merged.
In the example a appears five times overall, but the answer is not a5. The
leading aaa and the trailing aa have other characters between them, so they
are different runs. That is why a appears twice in the result.
d is d1, not d.a12."abc" becomes
"a1b1c1"."a2" for "aab" is that bug.Implement compress(s). The input is an arbitrary string (digits and spaces included).