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
Reverse Prefix of Word INPUT word = "abcdefd" a 0 b 1 c 2 d 3 e 4 f 5 d 6 ch = "d" d Segment to reverse: index 0 to 3 "abcd" word = "abcdefd" ch = "d" ALGORITHM STEPS 1 Find ch in word Use find() to locate "d" idx = word.find(ch) = 3 2 Check if found idx != -1, so proceed 3 != -1 --> OK 3 Slice prefix Get word[0:idx+1] prefix = "abcd" 4 Reverse and concat Reverse prefix + suffix "dcba" + "efd" "abcd" --> "dcba" word[:idx+1][::-1] + word[idx+1:] Python slicing approach FINAL RESULT Result: "dcbaefd" d 0 c 1 b 2 a 3 e 4 f 5 d 6 Reversed segment Transformation: Before: "abcdefd" | V After: "dcbaefd" Output: "dcbaefd" OK - Prefix reversed! Key Insight: The built-in find() method returns the index of the first occurrence of a character, or -1 if not found. Using slicing with [::-1] reverses the string efficiently. Combine: reversed_prefix + remaining_suffix. TutorialsPoint - Reverse Prefix of Word | Built-in Find and Slice Approach Time Complexity: O(n) | Space Complexity: O(n)
Asked in
Google 12 Amazon 8 Microsoft 6
35.6K Views
Medium Frequency
~10 min Avg. Time
890 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