We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reverse Prefix of Word

Number: 2128

Difficulty: Easy

Paid? No

Companies: Apple, Optum


Problem Description

Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If ch does not exist in word, the string remains unchanged.


Key Insights

  • Identify the index of the first occurrence of ch.
  • If ch is found, reverse the substring from the beginning up to and including that index.
  • If ch is not found, return the original word without any modifications.
  • The problem can be solved using string slicing/reversal or two-pointer techniques.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(n) for storing the resulting string (depending on language and implementation).


Solution

We first search for the first occurrence of ch in the given word. If found, we reverse the substring from the beginning of the word until that index (inclusive) using slicing or a two-pointer technique. The reversed substring is then concatenated with the remainder of the original string. If ch is not present, the original string is returned without changes.


Code Solutions

# Function to reverse the prefix of the word up to and including the first occurrence of ch
class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        # Find the index of the first occurrence of ch in word
        index = word.find(ch)
        # If ch is not found, return the original word
        if index == -1:
            return word
        # Reverse the substring from 0 to index (inclusive) and concatenate with the rest of the word
        return word[:index+1][::-1] + word[index+1:]
        
# Example usage
sol = Solution()
print(sol.reversePrefix("abcdefd", "d"))  # Output: "dcbaefd"
← Back to All Questions