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.