String Compression

Given an array of characters chars, compress it in place: for each group of consecutive repeating characters, write the character, followed by the group length if it is greater than 1 (lengths of 10 or more take several characters). Return the new length. Use only constant extra space.

30:00

String Compression
medium
Free written solution
Topics
Companies

Given an array of characters chars, compress it in place: for each group of consecutive repeating characters, write the character, followed by the group length if it is greater than 1 (lengths of 10 or more take several characters). Return the new length. Use only constant extra space.

Example 1:
Input: {"chars":["a","a","b","b","c","c","c"]}
Output: ["a","2","b","2","c","3"]
Constraints:
  • 1≤chars.length≤20001 \leq \text{chars.length} \leq 2000

  • chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"chars":["a","a","b","b","c","c","c"]}

chars, compressed in place

written output

current group

not yet read

a

a

b

b

c

c

c

0

1

2

3

4

5

6

write 0

read 0

write never passes read: a group of k copies needs 1 + digits(k) slots, and k is at least that whenever k > 1.

Groups read so far

No group finished yet.

Pointers

read = 0

write = 0

chars[0:write]

Variables
VariableValue
read0
write0
n7
DepthFunction Call
Stack empty
0/17