Reverse Prefix of Word — LeetCode 2000 Python Solution

EasyStackTwo PointersString
Problem
#2000
Pattern
Stack
Reading time
2 min

The 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.

Example

Input
word = "abcdefd", ch = "d"
Output
"dcbaefd"
Explanation
The first occurrence of "d" is at index 3.

Python solution

Python
class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        i = word.find(ch)
        return word if i == -1 else word[i::-1] + word[i + 1 :]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2000. Reverse Prefix of Word is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2000. Reverse Prefix of Word?
LeetCode 2000. Reverse Prefix of Word is rated Easy on LeetCode.
What is the time complexity of LeetCode 2000. Reverse Prefix of Word?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2000. Reverse Prefix of Word?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2000. Reverse Prefix of Word cover?
LeetCode 2000. Reverse Prefix of Word is tagged Stack, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview