String Compression

Medium

Topics
StringTwo Pointers

Shorten a string of letters by run-length encoding. Split s into maximal runs of the same character. Write each run as its character, followed by the run's length in decimal only when the length is 2 or more. A run of one character is written as just that character. Return the encoded string.

Letters are case-sensitive, so "a" and "A" are different characters. A run longer than 9 contributes all of its digits, for example twelve bs become "b12".

On this judge you return the encoded string. The common in-place variant writes the same encoding into the input array and returns its length; the run-splitting logic is identical.

Example 1

inxxyzzz
outx2yz3
Each run becomes its character plus its length, and a run of one gets no number at all — that exception is what stops the output growing. A count of 10 or more spans several output characters, which matters when writing back in place. Result: x2yz3.
The string before and after compression.
Input:  s = "xxyzzz"
Output: "x2yz3"

Example 2

inq
outq
Input:  s = "q"
Output: "q"

Example 3

inmnnnnnnnnnnnnn
outmn13
Input:  s = "mnnnnnnnnnnnnn"
Output: "mn13"
Explanation: One m, then thirteen n.

Constraints

  • 1 <= s.length <= 2000
  • s consists of uppercase and lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A run ends exactly where the next character differs from the current one. So one left-to-right pass with a pointer at the start of the current run is enough: advance a second pointer until the character changes, and the distance between them is the run length.

Approach

  1. Set i = 0.
  2. Move j forward from i while s[j] == s[i].
  3. Append s[i], then append j - i as decimal text if it is greater than 1.
  4. Set i = j and repeat until the end. Build the output in a string builder or list rather than with repeated concatenation.

Dry Run

s = "xxyzzz"
  s[0..1] is "xx"    run of 2   append the char and the count   out "x2"
  s[2..2] is "y"     run of 1   append the char only            out "x2y"
  s[3..5] is "zzz"   run of 3   append the char and the count   out "x2yz3"
answer "x2yz3"
The inner `while` finds the end of the run, so the outer loop jumps straight to
`i = j` and every character is examined once. That also means the final run is
flushed inside the loop rather than after it -- there is no leftover state to
handle on exit.
A run of ONE emits no count. That is the most common wrong answer here: append the
count unconditionally and "xxyzzz" becomes "x2y1z3", which is both longer than the
input and not what the problem asks for.
The count is appended as a string, not as a single character. `str(j - i)` handles
multi-digit runs, so twelve a's compress to "a12"; building the digit with
something like char('0' + count) silently breaks at 10.

Complexity

  • Time — O(n): each character is read once.
  • Space — O(n): for the output; the in-place variant needs O(1) because the encoding is never longer than the input.

Common Pitfalls

  • Appending a single digit with char('0' + count) breaks for runs of 10 or more.
  • Writing "a1" for a run of one is the most common wrong answer.
  • Forgetting to flush the final run after the loop.

Full Solution — all languages

class Solution:
    def compress(self, s):
        if not s:
            return ""
        out = []
        i = 0
        while i < len(s):
            j = i
            while j < len(s) and s[j] == s[i]:
                j += 1
            out.append(s[i])
            if j - i > 1:
                out.append(str(j - i))
            i = j
        return "".join(out)
SensAI
Beta
Tap the mic to stop voice mode