Reverse Prefix of Word
EasyPrompt
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"andch = "d", then you should reverse the segment that starts at0and ends at3(inclusive). The resulting string will be"dcbaefd".
Return the resulting string.
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 <= 250wordconsists of lowercase English letters.chis a lowercase English letter.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach uses built-in Java string methods to solve the problem. It first locates the target character ch. If found, it splits the word into two parts: the prefix (from the start up to and including ch) and the suffix (the rest of the string). The prefix is then reversed using a StringBuilder, and finally, the reversed prefix is concatenated with the suffix to form the result. If ch is not found, the original word is returned unmodified.
Algorithm
- Find the index of the first occurrence of
chusingword.indexOf(ch). - If
chis not found (index is -1), return the originalword. - Extract the prefix
word.substring(0, index + 1). - Create a
StringBuilderwith the prefix and reverse it usingreverse(). - Append the suffix
word.substring(index + 1)to the reversed prefixStringBuilder. - Return the result by converting the
StringBuilderto a string.
Walkthrough
This method is straightforward because it leverages the power of Java's standard library. The indexOf method provides a quick way to find the boundary for the reversal. Once the boundary index is known, the string is conceptually split. The StringBuilder class is ideal for the reversal part as it is mutable and provides a convenient reverse() method. The final step is simply combining the reversed part with the untouched part of the string.
class Solution { public String reversePrefix(String word, char ch) { int index = word.indexOf(ch); if (index != -1) { // Create a StringBuilder from the prefix and reverse it. StringBuilder reversedPrefix = new StringBuilder(word.substring(0, index + 1)); reversedPrefix.reverse(); // Append the rest of the word (suffix). reversedPrefix.append(word.substring(index + 1)); // Return the result as a string. return reversedPrefix.toString(); } // If ch is not found, return the original word. return word; }}Complexity
Time
O(N), where N is the length of the `word`. The `indexOf` method takes O(N), `substring` can take up to O(N), `StringBuilder.reverse()` takes O(k) (where k is the prefix length), and `append` takes O(N-k). The overall complexity is dominated by these linear-time operations.
Space
O(N). Space is required for the `StringBuilder`'s internal character array, potentially for the substrings (depending on JVM implementation), and for the final resulting string. The total space is proportional to the length of the input string.
Trade-offs
Pros
Code is concise and highly readable due to the use of high-level APIs like
indexOf,substring, andStringBuilder.The logic is straightforward and easy to follow for those familiar with Java's string manipulation capabilities.
Cons
Less efficient in terms of memory and speed due to the creation of multiple intermediate string objects (
substringcalls) and aStringBuilderobject. String immutability in Java means each manipulation creates a new object.
This is a more memory and time-efficient approach. Instead of creating multiple substrings, it converts the entire word into a mutable character array. After finding the index of the character ch, it uses a classic two-pointer technique to reverse the prefix part of the array in-place. Finally, a new string is constructed from the modified character array.
Algorithm
- Find the index
kof the first occurrence ofch. - If
chis not found, return the originalword. - Convert the
wordinto a character arraychars. - Initialize two pointers,
left = 0andright = k. - While
left < right, swapchars[left]andchars[right], then incrementleftand decrementright. - Create and return a new string from the modified
charsarray.
Walkthrough
This approach is considered more optimal because it minimizes object creation overhead. By converting the string to a character array at the beginning, all modifications can be done on this single mutable data structure. The two-pointer swap is a standard and efficient algorithm for in-place reversal. left starts at the beginning of the prefix and right starts at the end. They move towards the center, swapping elements at each step, until the entire prefix is reversed. This avoids the cost of creating new string objects for prefixes and suffixes.
class Solution { public String reversePrefix(String word, char ch) { int right = word.indexOf(ch); // If the character is not found, no action is needed. if (right == -1) { return word; } // Convert string to char array for mutable operations. char[] chars = word.toCharArray(); int left = 0; // Use two pointers to reverse the prefix in-place. while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } // Convert the char array back to a string. return new String(chars); }}Complexity
Time
O(N), where N is the length of the `word`. `indexOf` is O(N), `toCharArray()` is O(N), the two-pointer reversal takes O(k) time where k is the prefix length (O(N) in the worst case), and `new String(char[])` is O(N). The total time complexity remains linear.
Space
O(N). A character array of size N is created to store a mutable copy of the string. This is the primary space overhead.
Trade-offs
Pros
More efficient than the string manipulation approach as it avoids creating multiple intermediate string objects. It only creates one character array and one final string.
The in-place reversal on the character array is a common and efficient pattern for such problems.
Cons
The code is slightly more verbose than the one-liner
StringBuilderapproach, as it requires manual implementation of the two-pointer swap logic.
Solutions
Solution
class Solution {public String reversePrefix(String word, char ch) { int j = word.indexOf(ch); if (j == -1) { return word; } char[] cs = word.toCharArray(); for (int i = 0; i < j; ++i, --j) { char t = cs[i]; cs[i] = cs[j]; cs[j] = t; } return String.valueOf(cs); }}class Solution {public: string reversePrefix(string word, char ch) { int i = word.find(ch); if (i != string ::npos) { reverse(word.begin(), word.begin() + i + 1); } return word; }};class Solution: def reversePrefix(self, word: str, ch: str) -> str: i = word . find(ch) return word if i == - 1 else word[i:: - 1] + word[i + 1:]Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.