Easy · Run-Length Encoding
Understand → Visualise → Practice.
Compress each maximal character run as the character followed by its count when the count exceeds one.
Walk the string; for each run of equal characters, write the character and, if the run is longer than one, its length.
From i, advance j while text[j] == text[i].
Append the character, plus the count j − i when it is more than 1.
Set i = j and repeat; join the pieces at the end.
O(n) time and O(n) space.
Writing '1' for single characters gives "a3b2c1", which is not the expected format.
Read the full guide first: Strings: Frequencies, Matching and Palindromes.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.