#541
Easy Algorithms Reverse string ii
Two Pointers String
53.4% acceptance
Feb 19, 2026
2337
4419
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn reverse_str(s: String, k: i32) -> String {
let k = k as usize;
let mut chars: Vec<char> = s.chars().collect();
let n = chars.len();
let mut i = 0;
while i < n {
let end = (i + k).min(n);
chars[i..end].reverse();
i += 2 * k;
}
chars.iter().collect()
}
}