Reverse Prefix of Word

Below is the step-by-step approach and code to reverse the segment of the given word that starts at index 0 and ends at the index of the first occurrence of the character ch.

Understanding the Problem

You are given a string word and a character ch. You need to reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch. If ch does not exist in word, return word as it is.

Solution Approach

  1. Find the First Occurrence of ch: Use the find method to get the index of the first occurrence of ch in word. If ch is not found, return word unchanged.
  2. Reverse the Segment: If ch is found, reverse the segment of word from index 0 to the found index (inclusive).
  3. Concatenate with the Remaining Part: Join the reversed segment with the remaining part of word.
  4. Return the Result: Return the resulting string.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        # Find the index of the first occurrence of ch
        index = word.find(ch)

        # If ch is not found, return word as it is
        if index == -1:
            return word

        # Reverse the segment from 0 to index (inclusive) and concatenate with the remaining part
        reversed_segment = word[0:index + 1][::-1]
        remaining_part = word[index + 1:]

        # Join the reversed segment with the remaining part
        result = reversed_segment + remaining_part

        return result

Key Takeaways

  • We have used the find method to locate the index of the first occurrence of ch.
  • We have reversed the desired segment of the string using slicing and joined it with the remaining part.
  • The code ensures that if ch is not found, no reverse operation is performed, and word is returned unchanged.

This code meets the problem’s constraints and requirements, providing a clear solution to reverse the specified segment of the given word.