↓Skip to main content
  1. LeetCode/

LeetCode 2000: Reverse Prefix of Word

·1 min· ·
LeetCode Easy Two-Pointers String Stack
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2024-05-01

  • Submissions: Accepted (first try)

Approach
#

i = word.find(ch) is -1 when absent; then word[:0] is empty and appending all of word returns it unchanged, so no special case is needed. By hand, swap [0, i] with converging pointers (Two Pointers Template 1).

My Solution
#

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

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • index raises when not found; find returns -1.

Interview Explanation
#

I find ch’s first index, reverse the prefix through it and append the rest; when absent, find returns -1, the prefix is empty, and the word comes back unchanged. Time O(n).

Related

LeetCode 844: Backspace String Compare
·2 mins
LeetCode Easy Two-Pointers String Stack Simulation
LeetCode 844 note: simulate backspaces with a stack; for O(1) space, walk from the end and count how many characters each # skips
LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D
LeetCode 557: Reverse Words in a String III
·1 min
LeetCode Easy Two-Pointers String
LeetCode 557 note: split on spaces, reverse each word, and join with spaces
LeetCode 345: Reverse Vowels of a String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 345 note: the same two pointers as LC 917, with the condition switched to “is a vowel” (both cases)
LeetCode 1047: Remove All Adjacent Duplicates In String
·1 min
LeetCode Easy String Stack
LeetCode 1047 note: if the stack top equals the current character both vanish, otherwise push it; after a removal the new top may cancel with the next character
LeetCode 1021: Remove Outermost Parentheses
·1 min
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 note: track depth instead of a stack; the ‘(’ raising depth from 0 to 1 and the ‘)’ lowering it from 1 to 0 are outermost, everything else stays