Reverse Prefix of Word - Problem
You're given a string word and a target character ch. Your task is to reverse the prefix of the string that starts from the beginning and ends at the first occurrence of the target character.
Think of it like finding a bookmark in a book - once you find the first occurrence of your target character, you need to reverse everything from the start up to and including that character. If the character doesn't exist in the string, leave it unchanged.
Example:
- Input:
word = "abcdefd",ch = "d" - The first 'd' is at index 3
- Reverse the prefix "abcd" โ "dcba"
- Result:
"dcbaefd"
This problem tests your understanding of string manipulation, character searching, and in-place reversal techniques.
Input & Output
example_1.py โ Basic Case
$
Input:
word = "abcdefd", ch = "d"
โบ
Output:
"dcbaefd"
๐ก Note:
The first occurrence of 'd' is at index 3. We reverse the prefix "abcd" to get "dcba", then append the remaining "efd" to get "dcbaefd".
example_2.py โ Character Not Found
$
Input:
word = "xyxzxe", ch = "z"
โบ
Output:
"zxyxxe"
๐ก Note:
The first occurrence of 'z' is at index 3. We reverse the prefix "xyxz" to get "zxyx", then append the remaining "xe" to get "zxyxxe".
example_3.py โ Character Not Present
$
Input:
word = "abcd", ch = "z"
โบ
Output:
"abcd"
๐ก Note:
Since 'z' doesn't exist in the string "abcd", we return the original string unchanged.
Constraints
- 1 โค word.length โค 250
- word consists of lowercase English letters
- ch is a lowercase English letter
Visualization
Tap to expand
Understanding the Visualization
1
Find the Bookmark
Scan through the pages to find where the bookmark (target character) is located
2
Mark the Boundaries
Place your left hand at the beginning and right hand at the bookmark position
3
Flip Pages
Swap pages from both hands, moving your hands closer to each other
4
Complete the Flip
Continue until your hands meet - the prefix is now reversed!
Key Takeaway
๐ฏ Key Insight: Use two pointers to efficiently reverse the prefix in-place, eliminating the need for extra space while maintaining optimal time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code