oneby7

Strings String basics

131. String Compression

Medium

You are given an array of characters chars. Compress it: replace every run of equal characters that sit next to each other by that character followed by the length of the run. A run of length 1 is written as the character alone, with no number after it. A length of 10 or more takes one character per digit, so a run of twelve a characters becomes the three characters a, 1, 2.

Write the compressed text into the start of chars itself, and return its length k. Only the first k characters of chars are checked. Whatever is left after them does not matter. Aim for O(1) extra memory.

The examples write chars as a string, so chars = "aabccc" is the array of the six characters a, a, b, c, c, c. The output shows the first k characters of chars after your function returns, in double quotes: "a2bc3" means you returned k = 5 and those are the first five characters.

Example 1

Input: chars = "xxxyzzzz"

Output: "x3yz4"

Explanation: The runs are xxx, y and zzzz. They become x3, y and z4, so you return 5 and chars starts with x, 3, y, z, 4.

Example 2

Input: chars = "bbbbbbbbbbbbc"

Output: "b12c"

Explanation: The twelve b characters become b followed by the two digits 1 and 2. The single c stays as it is, so you return 4.

Example 3

Input: chars = "abab"

Output: "abab"

Explanation: No two equal characters sit next to each other, so every run has length 1 and nothing changes. You return 4.

Check your understanding

Work out the answer for this input before you write any code.

chars = "aaabba"

Constraints

  • 1 ≤ chars.length ≤ 105
  • chars[i] is a printable ASCII character other than a space: a letter, a digit or a symbol such as # or !

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.