Skip to main content
Back to problems
#2138
Easy Algorithms

Divide a string into groups of size k

String Simulation
77.1% acceptance
Feb 25, 2026
796
31
A string s can be partitioned into groups of size k using the following procedure: The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each element can be a part of exactly one group. For the last group, if the string does not have k characters remaining, a character fill is used to complete the group. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn divide_string(s: String, k: i32, fill: char) -> Vec<String> {
    let k = k as usize;
    let s: Vec<char> = s.chars().collect();
    let n = s.len();
    let padded_n = (n + k - 1) / k * k;
    (0..padded_n)
      .step_by(k)
      .map(|i| {
        (i..i + k)
          .map(|j| if j < n { s[j] } else { fill })
          .collect()
      })
      .collect()
  }
}