Skip to main content
Back to problems
Leetcode
Medium
Strings
Arrays
Reverse Prefix Of Word

Reverse the prefix of a word up to the first occurrence of a given character.

Acceptance 0%
Problem Statement

Given a string word and a character ch, find the first occurrence of ch in word. If it exists, reverse the prefix of word from the start up to and including that occurrence, and keep the rest of the string unchanged. If ch does not appear in word, return the original string.

This is a straightforward string transformation problem that tests careful scanning and substring handling.

Input Format

  • A string word
  • A character ch

The task is to produce the transformed string after reversing the prefix ending at the first occurrence of ch.

Output Format

Return the resulting string after applying the prefix reversal rule.

Constraints

  • 1 <= word.length
  • word contains lowercase English letters
  • ch is a lowercase English letter
  • The first occurrence of ch is used, if present
Examples
Sample cases returned by the problem API.

Example 1

Input

word = "abcdefd", ch = "d"

Output

"dcbaefd"

Explanation

The first d appears at index 3. Reverse the prefix "abcd" to get "dcba", then append the remaining suffix "efd".

Example 2

Input

word = "xyxzxe", ch = "z"

Output

"zyxxze"

Explanation

The first z appears at index 3. Reversing "xyxz" gives "zxyx", and the remaining suffix is "xe".

Show 1 more example

Example 3

Input

word = "abcd", ch = "z"

Output

"abcd"

Explanation

The character z does not appear, so the string stays unchanged.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.