Skip to content

String Compression

MediumTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

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.

chars = ["a", "a", "b", "b", "c", "c", "c"]   →  6, chars starts with ["a", "2", "b", "2", "c", "3"]
chars = ["a"]                                 →  1, chars starts with ["a"]
chars = ["a", "b", "b", ... 12 b's]           →  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.