Skip to content
BytePatterns

Run Length Compression

MediumStrings#two-pointers#run-length-encoding~25m

Problem

Shrink a piece of text by replacing each run of identical characters with that character followed by the length of the run. A run of length one keeps the bare character with no number after it. Return the compressed text only when it is strictly shorter than the original; otherwise return the original unchanged.

Examples

Input:  text = "aaabccdddd"
Output: "a3bc2d4"
Why:    the lone b stays bare while the longer runs pick up a count
Input:  text = "abcd"
Output: "abcd"
Why:    compressing would not shrink anything, so the original wins
Input:  text = ""
Output: ""
Why:    edge case, there is no run to encode

Hints

0 / 3

Stuck on the idea rather than the code? String Compression covers it.