Tap here to switch tabs
Problem
Ask
Submissions

Problem: String Compression

med
30 min
Explore how to apply the two pointers technique to perform in-place string compression on character arrays efficiently. Understand handling groups of repeating characters and managing space while modifying the input array directly.

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 perform in-place string compression on character arrays efficiently. Understand handling groups of repeating characters and managing space while modifying the input array directly.

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.