Problem
Ask
Submissions

Problem: String Compression

Medium
30 min
Explore how to implement string compression using the two-pointers technique. Understand how to modify character arrays in place to achieve efficient compression while meeting space constraints and returning the compressed length.

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.

Problem
Ask
Submissions

Problem: String Compression

Medium
30 min
Explore how to implement string compression using the two-pointers technique. Understand how to modify character arrays in place to achieve efficient compression while meeting space constraints and returning the compressed length.

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.