Skip to the code
cf.
+25 XP

#110 Squash Repeated Characters

medium

A collaborative editor sends typed text over the network as an array of single characters, chars. To save bandwidth it squashes each run of the same character: the character is written once, followed by the run's length if the length is more than 1. A length of 12 is written as two characters, "1" and "2".

Write squash(chars) that rewrites chars in place into its squashed form and shortens the array to that length. The squashed form is never longer than the original, so it always fits. The tests check chars after your function runs.

Example 1

Input: chars = ["a","a","b","c","c","c"]
Output: ["a","2","b","c","3"]

Runs aa, b, ccc become a2, b, c3.

Example 2

Input: chars = ["x","y","z"]
Output: ["x","y","z"]

Every run has length 1, so nothing changes.

Constraints

  • 0 <= chars.length <= 2000
  • Each item is a single printable character.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).