MediumTwo PointersString

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Pack the Symbol Tape is our own problem on the technique behind String Compression: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free