You are given an array of single characters and asked to compress it in place using run-length encoding. For each block of consecutive equal characters, write the character once, and if the block is longer than one, follow it with the decimal digits of the block's length.
Perform the rewrite inside the same array and return the length of the compressed section. You may use only constant extra space beyond the input array itself.
Example 1
Input: chars = ["a","a","b","b","c","c","c"]
Output: 6
The runs "aa", "bb", and "ccc" compress to a2, b2, c3. The first six slots become ['a','2','b','2','c','3'] and the function returns 6.
Example 2
Input: chars = ["a","a","a","a","a","a","a","a","a","a","a","a"]
Output: 3
A run of twelve 'a' characters compresses to the three slots ['a','1','2'], since the count 12 is spelled out digit by digit.
Constraints
1 <= chars.length <= 2000chars[i] is a lowercase letter, uppercase letter, digit, or symbolThe compressed result always fits within the original arraySee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI