Reverse Prefix of Word Solution in Java

Language Options

C++ Solution |
Python Solution

Code Solution


class Solution {
  public String reversePrefix(String word, char ch) {
    final int i = word.indexOf(ch) + 1;
    return new StringBuilder(word.substring(0, i)) //
        .reverse()                                 //
        .append(word.substring(i))                 //
        .toString();
  }
}

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 is simple: given a word and a character, you need to reverse the part of the word that comes before (and includes) the first occurrence of that character. If the character isn’t found, just return the original word.

Imagine you’re at a party, and someone shouts your name. You turn around, but instead of just saying “Hi,” you decide to do a little dance move that involves reversing your steps before you greet them. That’s basically what this problem is asking you to do with words!

Approach

The code provided does the following:

  1. It finds the index of the character in the word.
  2. It creates a substring from the start of the word to that index.
  3. It reverses that substring.
  4. It appends the rest of the word after the character and returns the final result.

Time and Space Complexity

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

Space Complexity: O(n), as we are creating new strings for the reversed prefix and the final result.

Real-World Example

Think of it like this: you’re at a coffee shop, and you order a “Caramel Macchiato.” But then, you realize you want to add “Extra Whip” to your order. Instead of just saying it, you decide to do a little shimmy and say, “Caramel Macchiato with Extra Whip!” The “Caramel Macchiato” is your prefix, and the “Extra Whip” is what comes after. If you didn’t want to add anything, you’d just stick with your original order.

Similar Problems

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