Reverse Prefix of Word: Find and Flip
Reverse Prefix of Word is LeetCode 2000. You are given a 0-indexed string word and a character ch. Find the first occurrence of ch in word, then reverse the segment of word from index 0 up to and including that index. If ch does not exist in word, return word unchanged.
A few examples:
word = "abcdefd",ch = "d"produces"dcbaefd". The first'd'is at index 3, so you reverseword[0..3].word = "xyxzxe",ch = "z"produces"zxyxxe". The first'z'is at index 3, so you reverseword[0..3].word = "abcd",ch = "z"produces"abcd". The character'z'is not in the word, so nothing changes.
The approach
This problem breaks down into two clean steps:
- Find the index. Scan the string left to right for the first occurrence of
ch. If it is not found, return the original string immediately. - Reverse the prefix. Take the substring from index 0 through the found index (inclusive), reverse it, and concatenate it with the remainder of the string.
That is all there is to it. You can use Python's built-in str.find() or str.index() for the search, and slicing with [::-1] for the reversal. Alternatively, you can convert the string to a list and use a two-pointer swap to reverse the prefix in place, which is the same technique you would use in Reverse String.
The two-pointer version places one pointer at index 0 and another at the index where ch was found. Swap the characters at both pointers, then move them toward each other until they meet. This performs the reversal without creating a reversed copy.
Python solution
def reverse_prefix(word, ch):
idx = word.find(ch)
if idx == -1:
return word
return word[:idx + 1][::-1] + word[idx + 1:]
This version uses slicing, which is concise and readable. The find call returns -1 if ch is absent, so the early return handles that case.
Here is the two-pointer version that works on a list of characters:
def reverse_prefix(word, ch):
idx = word.find(ch)
if idx == -1:
return word
chars = list(word)
left, right = 0, idx
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return "".join(chars)
Visual walkthrough
Here is the algorithm traced step by step on the input word = "abcdefd", ch = "d".
Step 1: Scan for the first occurrence of ch
Walk through the string left to right. The character 'd' first appears at index 3.
Step 2: Identify the prefix to reverse
The prefix is word[0..3] = "abcd". Everything from index 4 onward stays in place.
Step 3: Reverse the prefix
Reversing "abcd" gives "dcba". The rest of the string "efd" is untouched.
Step 4: Return the result
Concatenate "dcba" + "efd" = "dcbaefd". This is the final answer.
The total work is one scan to find ch and one pass to reverse the prefix. Both are linear in the length of the prefix, and the rest of the string is never touched.
Complexity analysis
| Metric | Value | Why |
|---|---|---|
| Time | O(n) | Finding ch scans at most n characters. Reversing the prefix takes at most n/2 swaps. |
| Space | O(n) | Strings in Python are immutable, so creating the result requires O(n) space. The two-pointer version also uses O(n) for the character list. |
If you are working in a language with mutable strings (like C++ or Rust), you can reverse the prefix in place and achieve O(1) extra space.
Building blocks
Reverse Prefix of Word combines two fundamental operations that appear across many string and array problems.
Linear scan for the first occurrence
Finding the first index of a character is the simplest form of a search. The same pattern appears in Find the Index of the First Occurrence in a String, where you scan for a substring instead of a single character. In both cases, you walk left to right and stop as soon as you find a match.
In-place prefix reversal
Reversing a contiguous segment of an array or string using two pointers is a core building block. Reverse String applies it to the entire array. Reverse String II reverses every other chunk of size k. Here, you reverse only the prefix up to a found index. The swap logic is identical in all three cases. The only thing that changes is which portion of the array the two pointers are placed on.
Once you can write the two-pointer reversal from memory, problems that ask you to "reverse some segment" become a matter of figuring out the boundaries rather than figuring out the reversal itself.
Edge cases
Character not found. If ch does not appear in word, return word as-is. The find method returns -1, and the early return handles this.
Character at index 0. If ch is the very first character, the prefix is just that single character. Reversing a single character changes nothing, so the word is returned unchanged. This is correct without any special-case code.
Character at the last index. If ch only appears at the final position, the entire string is the prefix. Reversing the whole string is a valid result.
Single character word. word = "a", ch = "a". The prefix is the entire word, and reversing a single character is a no-op. Returns "a".
All characters are the same. word = "aaaa", ch = "a". The first occurrence is at index 0, so the prefix is just "a". Reversing it changes nothing. Returns "aaaa".
From understanding to recall
This problem is easy to understand, and the solution is short. But that is exactly what makes it dangerous to skip during review. Simple problems create a false sense of mastery. You think you will remember the approach, but two weeks later you hesitate over whether find returns -1 or None, or whether the slice should be [:idx] or [:idx + 1].
Spaced repetition catches these small details before they slip away. You solve the problem once, then revisit it at increasing intervals. Each time, you rebuild the solution from scratch rather than re-reading it. That active recall is what turns a five-minute read into lasting knowledge.
Related posts
- Reverse String -- The pure two-pointer reversal pattern that forms the core of this problem
- Reverse String II -- Applies the same reversal to alternating chunks, adding boundary logic
- Find the Index of the First Occurrence in a String -- The search step expanded to substrings instead of single characters