Problem
You get an array of characters chars. Compress the array in place. First, split chars into groups. A group is a sequence of equal characters that are next to each other.
For each group, write the character. If the group has more than one character, write the group length after the character. A length of 10 or more uses one item for each digit.
Write the compressed result at the start of chars, and return its length. The items after this length do not matter. Use only O(1) extra space.
In the examples, the output shows the returned length and then the first part of chars with this length.
Example 1
- Input:
- chars = ["x","x","x","y","z","z"]
- Output:
- [5,["x","3","y","z","2"]]
- Explanation:
- The groups are
xxx,yandzz. The groupyhas one character, so no number follows it.
Example 2
- Input:
- chars = ["m","m","m","m","m","m","m","m","m","m","m","m","n","n"]
- Output:
- [5,["m","1","2","n","2"]]
- Explanation:
- The group of
mcharacters has length 12. The digits1and2use one item each.
Example 3
- Input:
- chars = ["q"]
- Output:
- [1,["q"]]
Constraints
- 1 <= chars.length <= 2000
- chars[i] is a lowercase English letter, an uppercase English letter, a digit or a symbol.
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- Find the Index of the First Occurrence in a String
Coding · Boyer–Moore String-Search Algorithm · Knuth–Morris–Pratt Algorithm · String
- Permutation in String
Coding · Hash Table · Sliding Window · String
- Reverse String
Coding · String · Two Pointers
- Shortest Way to Form String
Coding · Binary Search · Greedy · String
Sources · 2 references
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
Morgan Stanley
LeetCode 443. String Compression
Reported Jan 9, 2026 · 1 source report
MID_LEVEL
Source snapshot: Nov 12, 2026
View source
LeetCode company tags · 5 records
Apple
String Compression
Reported date not specified · Source window: 3mo
Source snapshot: Oct 20, 2026
Source frequency score: 51.2. This is not an interview probability.
View sourceGoldman Sachs
String Compression
Reported date not specified · Source window: 6mo
Source snapshot: Oct 20, 2026
Source frequency score: 48. This is not an interview probability.
View sourcePinterest
String Compression
Reported date not specified · Source window: 6mo