array and hashmap November 20, 2022

Reverse prefix of word

Time O(n) Space O(1) Open original problem

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)