MediumPythonJavaScriptTypeScript
Strings — String Compression (Run-Length)
AlgorithmsStringsTwo Pointers
solve(s) — compress s by replacing every run of the same character with the character
followed by the run length, but omit the length when it is 1. A run of 12 is written as the
character then 12 (two digits). Return the compressed string. The compressed string is
not replaced by the original when it is longer.
Scan with two indices: start marks the beginning of the current run, and i walks to the
end of it. When the character changes (or the string ends), emit the character and, if the run
is longer than 1, its length.
Examples
solve("aabbccc") → "a2b2c3"
solve("abbbbbbbbbbbb") → "ab12"
solve("aaabbaa") → "a3b2a2"
solve("abc") → "abc"Sample tests
Test #1Three runs
Input: ["aabbccc"]
Output: "a2b2c3"
Test #2Single character
Input: ["a"]
Output: "a"
Test #3Two-digit count
Input: ["abbbbbbbbbbbb"]
Output: "ab12"