Reverse Prefix of Word Solution in C++

Problem Description

So, you think you can just reverse a word, huh? Well, hold your horses! The “Reverse Prefix of Word” problem on LeetCode is here to test your skills. Imagine you’re at a party, and you hear your favorite song. You want to shout out the lyrics, but only up to a certain point—let’s say until your favorite word appears. The challenge is to reverse everything you’ve shouted so far, but only up to that word.

In simpler terms, given a string word and a character ch, you need to reverse the substring of word that starts from the beginning and ends at the first occurrence of ch. If ch is not found, just return the original word. Easy-peasy, right?

Code Solution


class Solution {
 public:
  string reversePrefix(string word, char ch) {
    reverse(word.begin(), word.begin() + word.find(ch) + 1);
    return word;
  }
};

Approach

The approach here is as straightforward as it gets. The code uses the reverse function from the C++ Standard Library to reverse the substring of word from the beginning to the position of the first occurrence of ch. If ch is not found, the find function will return string::npos, and the code will simply reverse the entire string, which is not what we want. But hey, that’s life!

Time and Space Complexity

Time Complexity

O(n), where n is the length of the string word. This is because we may need to traverse the entire string to find ch and then reverse the substring.

Space Complexity

O(1), as we are not using any additional data structures that grow with the input size.

Real-World Example

Imagine you’re at a karaoke night, and you’re belting out your favorite tune. You only want to sing the part of the song until your favorite word pops up. If you mess up and sing too much, you might just end up reversing your reputation instead! This problem is like that—only sing (or reverse) until you hit that magical word.