Maintained by Vikas Dulgunde, software engineer
You are given a string of lowercase letters. Walk through it and collapse every run of the same character that repeats back to back into the character followed by how many times it appeared in that run. When a character appears only once in a run, write the character alone with no number after it.
The catch is that this kind of encoding does not always save space. Short inputs with no real repetition can come out longer once the counts are stitched in. To guard against that, compare the length of the encoded result against the original.
If the encoded string is strictly shorter than the input, return the encoded string. If it is the same length or longer, return the original input untouched. The comparison is strict, so a tie counts as no improvement and the original wins.
Runs are aa, b, ccc, dddd, which encode to a2, b, c3, d4. The result has length 7 against the original 10, so the shorter encoded form is returned.
Every character is its own run of one, so encoding gives a1b1c1 at length 6. That is longer than the original length 3, so the input comes back unchanged.
Encoding produces a2b2, which is length 4, exactly equal to the input. Equal is not strictly shorter, so the original is returned.
Visible test cases
Scan the string left to right and group together stretches where the current character matches the previous one. You only need to know where each group starts and how long it is.
Build the encoded output piece by piece: for each group append the character, then append the count only when the count is greater than one.
Once the encoded string is fully built, do a single length comparison. Return the encoded form only if its length is strictly less than the original, otherwise return the input as is.
For each position, count how many of the same character follow it by re-scanning ahead, append the segment, and skip past the run. It works but the bookkeeping is clumsier than a clean single sweep.
Use one pointer to mark the start of a run and a second to extend it while characters match. Each character is visited a constant number of times, and the result is assembled in one clean sweep.