String Compression - Problem

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

  • If the group's length is 1, append the character to s.
  • Otherwise, append the character followed by the group's length.

The compressed string s should not be returned separately, but instead, be stored in the input character array chars.

Note: Group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

You must write an algorithm that uses only constant extra space.

Input & Output

Example 1 — Basic Compression
$ Input: chars = ["a","a","b","b","c","c","c"]
Output: 6
💡 Note: Groups: 'a' appears 2 times, 'b' appears 2 times, 'c' appears 3 times. Compressed: ['a','2','b','2','c','3']. Length is 6.
Example 2 — Single Characters
$ Input: chars = ["a"]
Output: 1
💡 Note: Single character 'a' with count 1, so no count is appended. Result: ['a']. Length is 1.
Example 3 — Mixed Groups
$ Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: 4
💡 Note: 'a' appears 1 time (no count), 'b' appears 12 times. Compressed: ['a','b','1','2']. Length is 4.

Constraints

  • 1 ≤ chars.length ≤ 2000
  • chars[i] is a lowercase English letter, uppercase English letter, or digit

Visualization

Tap to expand
String Compression OverviewInput Array:aaabbcCompressCompressed Array:a3b2cReturn Length: 53 a's2 b's1 c
Understanding the Visualization
1
Input
Array of characters with consecutive duplicates
2
Process
Count consecutive groups and compress
3
Output
Return new length of compressed array
Key Takeaway
🎯 Key Insight: Compressed form is never longer than original, so we can modify in-place
Asked in
Microsoft 35 Amazon 28 Google 22 Apple 18
68.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen