Reverse prefix of word
November 20, 2022
array-and-hashmapProblem URL: Reverse prefix of word
We will iterate through the word and check if the current character is equal to the first character of the prefix. If it is, we will reverse the prefix and return the word.
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
if ch not in word:
return word
i = word.index(ch)
return word[i::-1] + word[i+1:]
Time complexity: O(n)
Space complexity: O(1)