Array / String· 25 min

String Compression

LeetCode #443 · Medium · Interactive step-by-step visualization

Setup

Example inputchars = ["a","a","b","b","c","c","c"]
Step 1 / 7

Current step

1 / 7

Measure the 'a' run. Equal adjacent characters form one compressed group. Run [0..1] has length 2.

Step log

chars (read)

Cursor
Write
a
0
a
1
b
2
b
3
c
4
c
5
c
6

compressed (write)

No values to display.

character

a

count

2

Active cursor
Comparing
Best or completed
Leaving or removed
string-compression.java
1public int compress(char[] chars) {
2 int read = 0, write = 0;
3 while (read < chars.length) {
4 int start = read;
5 while (read < chars.length && chars[read] == chars[start]) read++;
6 chars[write++] = chars[start];
7 int count = read - start;
8 if (count > 1)
9 for (char digit : String.valueOf(count).toCharArray()) chars[write++] = digit;
10 }
11 return write;
12}
● Java
Time
O(n)
Space
O(1) extra
Pattern
array scan
Frames
7