Reverse Prefix of Word (LeetCode 2000): Solution and Explanation
Find the first occurrence of ch in word and reverse everything from index 0 up to and including it. If ch is not in word, return word unchanged.
Intuition
The problem splits word into two parts at the first ch. The part before and including ch is reversed, and the part after it is copied as it is. Nothing else about the string changes.
So the work is two small jobs. First, locate the index j of the first ch with a left to right scan (or the built-in find). If there is no such index, the answer is word itself.
Second, reverse word[0..j]. A stack does this naturally: push the characters in order, and when you pop them they come out last to first. The last character pushed is ch, so the answer always starts with ch.
Finally glue the reversed prefix to word[j + 1:], which never moved.
Approach: Find the first ch, reverse the prefix with a stack
- Let
jbe the index of the firstchinword. If there is none, returnword. - Push
word[0],word[1], ...,word[j]onto a stack. - Pop until the stack is empty, appending each popped character to the output.
- Append
word[j + 1:]and return the result.
Step-by-step example
word = "abcdefd", ch = "d"
- Scan: a, b, c are not d. The first d is at index 3, so j = 3 and the prefix is
abcd. - Push a, b, c, d. The stack from bottom to top is a b c d.
- Pop d, then c, then b, then a. The output is
dcba. - Append the suffix
efdthat comes after index 3. - Return
dcbaefd.
Code: Python, Java, C++
1class Solution:
2 def reversePrefix(self, word: str, ch: str) -> str:
3 j = word.find(ch)
4 if j == -1:
5 return word
6 stack = []
7 for i in range(j + 1):
8 stack.append(word[i])
9 out = []
10 while stack:
11 out.append(stack.pop())
12 return ''.join(out) + word[j + 1:]1class Solution {
2 public String reversePrefix(String word, char ch) {
3 int j = word.indexOf(ch);
4 if (j == -1) {
5 return word;
6 }
7 Deque<Character> stack = new ArrayDeque<>();
8 for (int i = 0; i <= j; i++) {
9 stack.push(word.charAt(i));
10 }
11 StringBuilder out = new StringBuilder();
12 while (!stack.isEmpty()) {
13 out.append(stack.pop());
14 }
15 out.append(word.substring(j + 1));
16 return out.toString();
17 }
18}1class Solution {
2public:
3 string reversePrefix(string word, char ch) {
4 int j = (int) word.find(ch);
5 if (j == -1) {
6 return word;
7 }
8 stack<char> st;
9 for (int i = 0; i <= j; i++) {
10 st.push(word[i]);
11 }
12 string out;
13 while (!st.empty()) {
14 out += st.top();
15 st.pop();
16 }
17 out += word.substr(j + 1);
18 return out;
19 }
20};Time and space complexity
O(n)
Finding ch reads at most n characters, and each prefix character is pushed and popped once. The suffix is copied once.
O(n)
The stack holds up to n characters and the output string has n characters. The two-pointer version reverses a character array in place with O(1) extra space beyond the array.
Other approaches
Two pointers on a character array (time O(n), space O(n) for the array copy, O(1) extra)
Convert word to an array, set l = 0 and r = j, and swap while l < r. It is the classic in-place reverse and uses no stack.
Slicing (time O(n), space O(n))
In languages with slices, word[:j + 1][::-1] + word[j + 1:] is a one-liner. It does the same work with library calls.
Common mistakes
- Using the last occurrence of
chinstead of the first. Only the first one defines the prefix. - Excluding
chitself from the reversal. The range is inclusive, so the result starts withch. - Forgetting the case where
chis missing.findreturns -1, and slicing withj + 1 = 0happens to work in Python, but other languages may throw or reverse the wrong range, so return early. - Dropping the suffix after
jwhen building the answer.
Frequently asked questions
Why use a stack when two pointers work?
Both are O(n). The stack makes the reversal obvious: last in, first out turns abcd into dcba. Two pointers save the extra memory, which is a good follow-up to mention.
What if ch is the first character?
Then j = 0 and the prefix is a single character. Reversing one character changes nothing, so the answer equals word.
What if ch appears several times?
Only the first occurrence counts. Later copies of ch sit in the suffix and are left in place.