#2109
Medium Algorithms Adding spaces to a string
Array Two Pointers String Simulation
71.8% acceptance
Feb 25, 2026
1116
113
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.
For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain "Enjoy Your Coffee".
Return the modified string after the spaces have been added.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn add_spaces(s: String, spaces: Vec<i32>) -> String {
let s = s.as_bytes();
let mut result = Vec::with_capacity(s.len() + spaces.len());
let mut sp_idx = 0;
for (i, &c) in s.iter().enumerate() {
if sp_idx < spaces.len() && spaces[sp_idx] == i as i32 {
result.push(b' ');
sp_idx += 1;
}
result.push(c);
}
String::from_utf8(result).unwrap()
}
}