Reverse Prefix of Word - Problem
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive).
If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".
Return the resulting string.
Input & Output
Example 1 — Basic Case
$
Input:
word = "abcdefd", ch = "d"
›
Output:
"dcbaefd"
💡 Note:
The first 'd' appears at index 3. Reverse segment [0..3]: 'abcd' → 'dcba', then append 'efd' to get 'dcbaefd'.
Example 2 — Character Not Found
$
Input:
word = "xyxzxe", ch = "z"
›
Output:
"zyxxzxe"
💡 Note:
First 'z' at index 2. Reverse prefix [0..2]: 'xyx' → 'yxx', then prepend 'z': 'zyxx', append 'xe' to get 'zyxxzxe'.
Example 3 — Character at Start
$
Input:
word = "abcd", ch = "a"
›
Output:
"abcd"
💡 Note:
Target 'a' is at index 0. Reversing segment [0..0] gives 'a', so result remains 'abcd'.
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
Input
String 'abcdefd' and target character 'd'
2
Find & Reverse
Locate first 'd' at index 3, reverse prefix 'abcd' → 'dcba'
3
Output
Concatenate reversed prefix with suffix: 'dcbaefd'
Key Takeaway
🎯 Key Insight: Only reverse the prefix up to the first occurrence of the target character, leaving the rest unchanged.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code