Skip to main content
Back to problems
#2000
Easy Algorithms

Reverse prefix of word

Two Pointers String Stack
86.5% acceptance
Feb 25, 2026
1502
46
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". Return the resulting string.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_prefix(word: String, ch: char) -> String {
    if let Some(idx) = word.find(ch) {
      let mut chars: Vec<char> = word.chars().collect();
      chars[..=idx].reverse();
      chars.into_iter().collect()
    } else {
      word
    }
  }
}