Magicsheet logo

Reverse Prefix of Word

Easy
100%
Updated 6/1/2025

Reverse Prefix of Word

What is this problem about?

The Reverse Prefix of Word interview question gives you a string word and a character ch. Find the first occurrence of ch in word and reverse the entire prefix of word up to and including that character. If ch does not appear in word, return the original word unchanged.

Why is this asked in interviews?

This problem is asked at Optum, Microsoft, Amazon, Google, and Bloomberg as a beginner-level string manipulation question. It tests understanding of string reversal, index finding, and slicing — fundamental skills applicable to text editors, parsing, and string processing utilities. It also serves as a warm-up to validate fluency with basic string operations.

Algorithmic pattern used

The pattern is prefix identification followed by in-place reversal. Find the index i of the first occurrence of ch using word.index(ch) or word.find(ch). If found, reverse word[0:i+1] and concatenate with word[i+1:]. If not found, return word unchanged. Using a stack or two-pointer reversal on the prefix also works as an alternative to slicing.

Example explanation

word = "abcdefd", ch = 'd'.

  • First occurrence of 'd': index 3.
  • Reverse word[0:4] = "abcd""dcba".
  • Append word[4:] = "efd".

Result: "dcbaefd".

word = "xyxzx", ch = 'z':

  • First occurrence of 'z': index 3.
  • Reverse "xyxz""zxyx".
  • Append "x".

Result: "zxyxx".

word = "abcd", ch = 'z':

  • 'z' not in word → return "abcd" unchanged.

Common mistakes candidates make

  • Using word.index(ch) without catching ValueError when ch is absent — use find() and check for -1 instead.
  • Reversing the wrong portion (e.g., reversing from index 0 to i exclusive instead of inclusive).
  • Off-by-one error in the slice: word[0:i+1] reverses up to and INCLUDING index i.
  • Forgetting to concatenate the unreversed suffix after the reversal.

Interview preparation tip

For the Reverse Prefix of Word coding problem, the two-pointer and string interview pattern applies cleanly. In Python, word[:i+1][::-1] + word[i+1:] is concise and readable. Bloomberg interviewers may ask for the two-pointer approach explicitly — practice reversing a prefix in-place on a character array. Always verify your index is inclusive with a quick trace on paper before finalizing your solution.

Similar Questions