Reverse Prefix of Word

easy string two pointers

Problem

You are given a lowercase string word and a single character ch. Locate the first position where ch appears in word and reverse the prefix that runs from index 0 through that position, inclusive; everything after it stays where it is. If ch never appears, return word unchanged.

Inputword = "abcdefd", ch = "d"
Output"dcbaefd"
The first 'd' sits at index 3, so the prefix "abcd" is reversed to "dcba" while the suffix "efd" is untouched.

def reverse_prefix(word, ch):
    j = word.find(ch)
    if j == -1:
        return word
    chars = list(word)
    left, right = 0, j
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return "".join(chars)
function reversePrefix(word, ch) {
  const j = word.indexOf(ch);
  if (j === -1) return word;
  const chars = word.split("");
  let left = 0, right = j;
  while (left < right) {
    [chars[left], chars[right]] = [chars[right], chars[left]];
    left++;
    right--;
  }
  return chars.join("");
}
String reversePrefix(String word, char ch) {
    int j = word.indexOf(ch);
    if (j == -1) return word;
    char[] chars = word.toCharArray();
    int left = 0, right = j;
    while (left < right) {
        char tmp = chars[left];
        chars[left++] = chars[right];
        chars[right--] = tmp;
    }
    return new String(chars);
}
string reversePrefix(string word, char ch) {
    size_t j = word.find(ch);
    if (j == string::npos) return word;
    int left = 0, right = (int)j;
    while (left < right) {
        swap(word[left], word[right]);
        left++;
        right--;
    }
    return word;
}
Time: O(n) Space: O(n)