Skip to main content
Back to problems
#443
Medium Algorithms

String compression

Two Pointers String
59.6% acceptance
Jan 13, 2026
6143
8844
Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars. After you are done modifying the input array, return the new length of the array. You must write an algorithm that uses only constant extra space. Note: The characters in the array beyond the returned length do not matter and should be ignored.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn compress(chars: &mut Vec<char>) -> i32 {
    let mut write = 0;
    let mut i = 0;
    
    while i < chars.len() {
      let current_char = chars[i];
      let mut count = 0;
      
      while i < chars.len() && chars[i] == current_char {
        i += 1;
        count += 1;
      }
      
      chars[write] = current_char;
      write += 1;
      
      if count > 1 {
        for digit in count.to_string().chars() {
          chars[write] = digit;
          write += 1;
        }
      }
    }
    
    write as i32
  }
}