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
The Bookmark Flip Methodword = "abcdefd", target = 'd'aPage 0bPage 1cPage 2dBookmark!ePage 4fPage 5dPage 6LRFlip these pages!After flipping: "dcbaefd"โœ“ Pages 0-3 are now in reverse orderโœ“ Remaining pages (4-6) stay in original position
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.
Asked in
Amazon 25 Microsoft 18 Google 15 Facebook 12
47.0K Views
Medium Frequency
~8 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen