Tap here to switch tabs
Problem
Ask
Submissions

Problem: String Compression

med
30 min
Explore how to apply the two pointers technique to compress strings directly within the input array. Learn to identify groups of repeating characters and represent counts efficiently, including multi-digit lengths. This lesson helps you master an in-place algorithm that uses constant extra space and returns the new length of the compressed array.

Statement

Given an array of characters, chars, compress it in place according to the following rules:

  1. Start with an empty string s.

  2. For each group of consecutive repeating characters in chars:

    1. If the group length is 11, append just the character to s.

    2. Otherwise, append the character followed by the group length.

The compressed string s should not be returned separately; instead, it must be written directly into the input character array chars. Note that if a group’s length is 1010 or greater, each digit of the length should be stored as a separate character in chars.

After modifying the array, return the new length of the compressed array.

Note: Your solution must use only constant extra space. Any characters beyond the returned length in chars can be ignored.

Constraints:

  • 11 \leq chars.length 2000\leq 2000

  • chars[i] is a lowercase English letter, an uppercase English letter, a digit, or a symbol.

Tap here to switch tabs
Problem
Ask
Submissions

Problem: String Compression

med
30 min
Explore how to apply the two pointers technique to compress strings directly within the input array. Learn to identify groups of repeating characters and represent counts efficiently, including multi-digit lengths. This lesson helps you master an in-place algorithm that uses constant extra space and returns the new length of the compressed array.

Statement

Given an array of characters, chars, compress it in place according to the following rules:

  1. Start with an empty string s.

  2. For each group of consecutive repeating characters in chars:

    1. If the group length is 11, append just the character to s.

    2. Otherwise, append the character followed by the group length.

The compressed string s should not be returned separately; instead, it must be written directly into the input character array chars. Note that if a group’s length is 1010 or greater, each digit of the length should be stored as a separate character in chars.

After modifying the array, return the new length of the compressed array.

Note: Your solution must use only constant extra space. Any characters beyond the returned length in chars can be ignored.

Constraints:

  • 11 \leq chars.length 2000\leq 2000

  • chars[i] is a lowercase English letter, an uppercase English letter, a digit, or a symbol.