Strings String basics
131. String Compression
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"
"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"
"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"
"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.
Constraints
1 ≤ chars.length ≤ 105chars[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.