#3794
Easy Algorithms Reverse string prefix
Two Pointers String
89.4% acceptance
Mar 15, 2026
41
1
You are given a string s and an integer k.
Reverse the first k characters of s and return the resulting string.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn reverse_prefix(s: String, k: i32) -> String {
let k = k as usize;
let mut chars: Vec<char> = s.chars().collect();
chars[..k].reverse();
chars.into_iter().collect()
}
}