Reverse Prefix of Word

two-pointers

Description

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. Return the resulting string.

Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of 'd' is at index 3. Reverse the prefix [0..3]: "abcd" -> "dcba". Result: "dcba" + "efd" = "dcbaefd".

Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first 'z' is at index 3. Reverse prefix [0..3]: "xyxz" -> "zxyx". Result: "zxyx" + "xe" = "zxyxxe".

Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: 'z' does not exist in word, so return original string.

Constraints

  • 1 <= word.length <= 250
  • word consists of lowercase English letters
  • ch is a lowercase English letter

Complexity

Show Complexity
  • Time: O(n)
  • Space: O(n)

Hints

Show Hints
Pattern
Find index then two-pointer reverse
Approach
Find first occurrence of ch. If found, reverse substring from index 0 to that index using two pointers.
Complexity
First find ch, then reverse prefix using two pointers

Solutions

Show PY Solution
def solution(word, ch):
    results = list(word)

    for right in range(len(results)):
        if results[right] == ch:
            i, j = 0, right
            while i < j:
                results[i], results[j] = results[j], results[i]
                i += 1
                j -= 1
            break

    return "".join(results)