Reverse Prefix of Word - Complete Solution Guide
Reverse Prefix of Word is LeetCode problem 2000, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 the character ch does not exist in word , do nothing. For example, if word = "abcdefd" and ch = "d" , then you should reverse the segment that starts at 0 and ends at 3 ( inclusive ). The resulting string will be " dcba efd" . Return the resulting string . Example 1: Input: word = " abcd efd", ch = "d" Output: " dcba efd" Expl
Detailed Explanation
The problem asks you to reverse a prefix of a given string. The prefix extends from the beginning of the string up to and including the first occurrence of a specified character. If the specified character is not found in the string, the string remains unchanged. The input consists of a string `word` and a character `ch`. The output is the modified string with the reversed prefix.
Solution Approach
The solutions generally follow these steps: First, find the index of the first occurrence of character `ch` in the string `word`. If `ch` is not found, return the original string. Otherwise, reverse the substring from the beginning of `word` up to and including the found index. Finally, concatenate the reversed prefix with the remaining suffix of the original string to form the result.
Step-by-Step Algorithm
- Find the index of the first occurrence of character `ch` in the string `word` using either `word.index(ch)` (Python) or `word.indexOf(ch)` (Java) or a manual loop (C++ and C).
- If the character `ch` is not found (index is -1), return the original string `word`.
- If `ch` is found, reverse the substring from index 0 to the found index (inclusive). This can be done either in-place using two pointers (Java, C, C++) or by creating a reversed substring and concatenating (Python).
- Concatenate the reversed prefix with the remaining part of the original string (from the index after the found character to the end) to get the final result.
Key Insights
- The problem can be efficiently solved using string manipulation techniques and finding the index of the first occurrence of a character.
- The choice of using either in-place reversal (like in the Java and C solutions) or creating a new reversed substring (like in the Python solution) impacts space complexity.
- Handling the case where the specified character `ch` is not present in the input string `word` is crucial to avoid errors.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Two Pointers, String, Stack.
Companies
Asked at: Optum.