↓Skip to main content
  1. LeetCode/

LeetCode 3794: Reverse String Prefix

·2 mins· ·
LeetCode Easy Two-Pointers String
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: 2026-01-03

  • Submissions: Accepted (slicing) → Runtime Error ×2 → Accepted (two pointers, 2026-01-24)

Approach
#

Reverse the first k characters. Python slicing does it in one line: s[:k][::-1] + s[k:].

My Attempts: rewriting with two pointers for practice
#

When I came back in late January to rewrite it with two pointers, two Runtime Errors followed:

  1. right = len(k) - 1: k is an integer and has no len; it should be k - 1.
  2. After that, s[left], s[right] = s[right], s[left] failed: Python strings cannot be modified, so convert with list(s) first and "".join(...) at the end.

Solution
#

class Solution:
    def reversePrefix(self, s: str, k: int) -> str:
        chars = list(s)
        left, right = 0, k - 1
        while left < right:
            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1
        return "".join(chars)

Complexity
#

Time O(n), space O(n) (strings are immutable, so a new one is always built).

Mistakes to Avoid
#

  • Assigning to characters of a string: Python strings are immutable.
  • Calling len on an integer.

Interview Explanation
#

Python strings are immutable, so I convert to a list and swap with two pointers from index 0 and index k - 1 toward the middle, then join back into a string. Slicing, s[:k][::-1] + s[k:], also works; both are O(n).

Related

LeetCode 1768: Merge Strings Alternately
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 1768 note: take characters in turn with one index, then append whatever remains of the longer string
LeetCode 917: Reverse Only Letters
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 917 note: two pointers each skip non-letters and swap when both point at letters; convert the string to a list first
LeetCode 925: Long Pressed Name
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 925 note: one pointer each over name and typed; every typed character either matches the next name character or repeats the previous typed character
LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum
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 680: Valid Palindrome II
·2 mins
LeetCode Easy Two-Pointers String Greedy
LeetCode 680 note: at the first mismatch the only options are deleting the left or the right character; check whether either remainder is a palindrome