MediumTwo PointersString

String Compression

LeetCode
1 approach, code in all languages

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 <= 2000
  • chars[i] is a lowercase letter, uppercase letter, digit, or symbol
  • The compressed result always fits within the original array
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now