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:
"zxyxze"
💡 Note:
First 'z' at index 3. Reverse prefix [0..3]: 'xyxz' → 'zxyx', then append 'xe' to get 'zxyxze'.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code