Meta Data#
Difficulty: easy First Attempt: 2024-05-01
- Submissions: Accepted (first try)
Approach#
i = word.find(ch) is -1 when absent; then word[:0] is empty and appending all of word returns it unchanged, so no special case is needed. By hand, swap [0, i] with converging pointers (Two Pointers Template 1).
My Solution#
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
i = word.find(ch)
return word[:i + 1][::-1] + word[i + 1:]
Complexity#
Time O(n), space O(n).
Mistakes to Avoid#
indexraises when not found;findreturns -1.
Interview Explanation#
I find ch’s first index, reverse the prefix through it and append the rest; when absent, find returns -1, the prefix is empty, and the word comes back unchanged. Time O(n).
