Reverse Prefix of Word

Updated on 14 July, 2025
Reverse Prefix of Word header image

Problem Statement

In this problem, we are given a string word that begins at the 0th index, and a character ch. The goal is to reverse the portion of word from the start (0-index) to the position where the character ch first appears, including that character's position. If the specified character ch does not appear at all within word, then the string remains unchanged. After performing this operation, the resulting string should be returned. This manipulation challenges us to identify and modify specific segments of a string based on character occurrence, providing insight into string handling and the reversal process in programming.

Examples

Example 1

Input:

word = "abcdefd", ch = "d"

Output:

"dcbaefd"

Explanation:

 The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".

Example 2

Input:

word = "xyxzxe", ch = "z"

Output:

"zxyxxe"

Explanation:

 The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".

Example 3

Input:

word = "abcd", ch = "z"

Output:

"abcd"

Explanation:

 "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".

Constraints

  • 1 <= word.length <= 250
  • word consists of lowercase English letters.
  • ch is a lowercase English letter.

Approach and Intuition

To solve the problem efficiently, let's follow these steps:

  1. Search for the Character:

    • Check if the character ch is present in the word.
    • If found, record the index of its first occurrence (indexCh).
  2. Conditionally Reverse the Segment:

    • If ch is not found, the string remains as is, and can be returned immediately.
    • If ch is found, split the string into two parts:
      • The part from the start of the word to indexCh.
      • The remaining part from indexCh+1 to the end.
    • Reverse the first part.
  3. Concatenate and Return:

    • Concatenate the reversed segment with the unchanged latter part of the string to form the final result.

Key Points:

  • Only the sub-sequence from the start of the string to the first occurrence of ch is modified.
  • The rest of the string remains unchanged.
  • If ch is absent in the string, no operations are required.

Example walkthroughs illustrate how this approach is directly applied:

  • In the first example with word = "abcdefd" and ch = "d", the reversal occurs up to the first 'd' at index 3, transforming "abcd" to "dcba" and resulting in "dcbaefd".
  • If the character ch does not exist in the string as in the third example where word = "abcd" and ch = "z", the output remains "abcd" because no reversal is necessary.

Solutions

  • C++
cpp
class Solution {
public:
    string reversePrefix(string str, char delimiter) {
        int startIndex = 0;
    
        for (int endIndex = 0; endIndex < str.length(); endIndex++) {
            if (str[endIndex] == delimiter) {
                while (startIndex < endIndex) {
                    swap(str[startIndex], str[endIndex]);
                    startIndex++;
                    endIndex--;
                }
                return str;
            }
        }
        return str;
    }
};

The provided C++ solution is designed to reverse the prefix of a string up until a specified delimiter character. The function reversePrefix, defined within the Solution class, accepts two arguments: a string str and a character delimiter.

Follow these general steps to understand the implementation:

  1. Initialize startIndex to 0 to track the beginning of the string.
  2. Use a for loop with a variable endIndex iterating over the string to locate the delimiter character.
  3. When the delimiter is found, engage a nested loop that swaps characters from startIndex to endIndex, effectively reversing the segment.
  4. Increment startIndex and decrement endIndex concurrently within the loop to move towards the center from both ends, ensuring the substring's characters are reversed.
  5. Upon completing the reversal or if the delimiter is not found, the modified string is returned.

This function makes a direct modification to the input string and handles the scenario where the delimiter does not exist by returning the string unchanged. The approach is efficient, leveraging in-place character swaps to perform the reversal without needing additional memory for substring manipulation.

  • Java
java
public class Solution {
    public String reversePrefix(String str, char delimiter) {
        char[] arr = str.toCharArray();
        int start = 0;
    
        for (int end = 0; end < str.length(); end++) {
            if (arr[end] == delimiter) {
                while (start < end) {
                    charSwap(arr, start, end);
                    start++;
                    end--;
                }
                return new String(arr);
            }
        }
        return str;
    }
    
    private void charSwap(char[] array, int pos1, int pos2) {
        char hold = array[pos2];
        array[pos2] = array[pos1];
        array[pos1] = hold;
    }
}

The provided Java code aims to reverse the prefix of a word up to a specified delimiter character and return the modified string. The method reversePrefix takes two parameters: a string str and a character delimiter. It reverses the sequence of characters in str from the beginning up to the first occurrence of delimiter.

  • Steps for Execution:

    1. Convert string str to a character array arr to facilitate character swapping.

    2. Initialize an integer start to track the beginning of the substring to reverse.

    3. Use a loop where end iterates through the characters in arr. Inside the loop, check if the current character matches the delimiter.

    4. If a match is found, use another loop to swap characters from start to end until they meet, effectively reversing the order of characters in that segment.

    5. Return the newly formed string constructed from array arr after the reversal.

  • If delimiter is not found in str, the method returns the original string unchanged.

The helper method charSwap aids in swapping characters in the array arr by taking the array itself and two positions (pos1 and pos2) of characters to swap. This method performs the swap by utilizing a temporary placeholder.

Ensure you handle edge cases such as scenarios where:

  • The delimiter does not exist in str.
  • The delimiter is at the start or end of str.
  • The str is empty or contains only one character.

By implementing the above mechanism, this Java solution efficiently handles the task of selectively reversing parts of a string based on a given delimiter.

  • Python
python
class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        seq = list(word)
        start = 0
    
        for end in range(len(word)):
            if seq[end] == ch:
                while start < end:
                    seq[end], seq[start] = seq[start], seq[end]
                    start += 1
                    end -= 1
                return "".join(seq)
        return word

In the Python solution provided for "Reverse Prefix of Word," a method reversePrefix is implemented within a Solution class. The method takes two parameters: word, a string, and ch, a character. It aims to reverse the portion of word that precedes the first occurrence of ch.

Follow these steps to understand the functionality:

  1. Convert the input string word into a list seq to facilitate in-place modifications.
  2. Initialize start to 0 to track the beginning of the sequence to reverse.
  3. Iterate over the indices (end) of the sequence.
  4. Check if the current character matches ch.
  5. If a match is found, use a while loop to reverse the segment from start to end:
    • Swap characters at positions start and end.
    • Increment start and decrement end to progressively narrow down the focused segment.
  6. Once the segment is reversed, or if ch is not found in word, convert the list back to a string and return it.

This approach efficiently locates and reverses the required segment and then immediately returns the modified word.

Comments

No comments yet.