Reverse Prefix of Word Solution in Python


Problem Description

So, you think you can just reverse a prefix of a word and call it a day? Well, welcome to the world of LeetCode, where even the simplest tasks can turn into a brain teaser! The problem at hand is to reverse the prefix of a given word up to a specified character. If that character doesn’t exist in the word, you just get to keep the word as is. It’s like trying to find your keys in a messy room—if you find them, great! If not, well, you’re still stuck with the mess.

Imagine you’re at a party, and you hear your favorite song. You rush to the dance floor, but wait! You trip over your own feet because you were too excited. That’s what this problem is about—finding that excitement (the character) and reversing your steps (the prefix) before you hit the floor (the rest of the word).

Code Solution


class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        i = word.find(ch) + 1
        return word[:i][::-1] + word[i:]

Approach

The approach here is as straightforward as it gets. The code first finds the index of the specified character in the word. If the character is found, it slices the word up to that index, reverses that slice, and then appends the rest of the word. If the character isn’t found, it simply returns the original word. It’s like taking a shortcut through a park—if you find the path (the character), you take it; if not, you just keep walking the same route.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the length of the word.
Space Complexity O(n), as we are creating a new string that could potentially be the same length as the input word.

Real-World Example

Let’s say you’re trying to send a text message, and you accidentally type “Hello, World!” but you want to reverse everything up to the comma. So, you’d end up with “,olleH World!”—a perfect example of reversing a prefix! Just like in our problem, if you find that comma, you reverse everything before it. If you don’t, well, you just send “Hello, World!” and hope for the best.

Similar Problems

If you enjoyed this problem, you might also like these: