String Compression

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: String Compression

Approach

Use a read pointer to scan groups of consecutive identical characters and a write pointer to overwrite the array in-place. For each group, write the character followed by its count digits (only if count exceeds 1). Return the write pointer as the new length.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Two Pointers (Read/Write)

Why It Works

The write pointer never overtakes the read pointer because the compressed form is always shorter or equal. Writing char + count digits in-place is safe since we have already read past those positions.

Updated Feb 2026