Description: Reverse Prefix of Word
Code:
def reversePrefix(self, word: str, ch: str) -> str:
if len(word) == 1:
return word
if ch not in word:
return word
left = 0
right = word.index(ch)
result = list(word)
while left < right:
result[left], result[right] = result[right], result[left]
left += 1
right -= 1
return ''.join(result)
Efficiency:
Time Complexity: O(n)
Space Complexity: O(n)
Test:
assert reversePrefix("abcdefd", "d") == "dcbaefd"
assert reversePrefix("xyxzxe", "z") == "zxyxxe"
assert reversePrefix("abcd", "z") == "abcd" # ch not found
assert reversePrefix("a", "a") == "a" # single character