Skip to content
Decoder

String Compression

Medium

Problem

You are given a list of characters chars. Compress it in place: for each run of consecutive repeating characters, write the character, then, if the run is longer than 1, write its length as digits (a run of 12 becomes "1", "2"). Return the new length k; the first k slots of chars must hold the compressed result.

Example 1

Input
chars = ["a", "a", "b", "b", "c", "c", "c"]
Output
6, chars starts with ["a", "2", "b", "2", "c", "3"]

Example 2

Input
chars = ["a"]
Output
1, chars starts with ["a"]

Example 3

Input
chars = ["a", "b", "b", ... 12 b's]
Output
4, chars starts with ["a", "b", "1", "2"]

Use only constant extra space.

Constraints

  • 1 <= chars.length <= 2000
  • chars[i] is a lowercase or uppercase letter, a digit, or a symbol.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.