LeetCode 344: Reverse String Solution in Python – A Step-by-Step Guide
Imagine you’re handed a string and asked to flip it around—like turning "hello" into "olleh" with a simple twist. That’s the challenge of LeetCode 344: Reverse String, an easy-level problem that introduces string manipulation with an in-place twist. Using Python, we’ll explore two solutions: the Best Solution, a two-pointer approach that’s efficient and elegant, and an Alternative Solution, a recursive method for a different perspective. With detailed examples, clear code, and a friendly tone—especially for the two-pointer breakdown—this guide will help you reverse that string, whether you’re new to coding or brushing up. Let’s dive into the characters and flip them around!
What Is LeetCode 344: Reverse String?
In LeetCode 344: Reverse String, you’re given a character array s
, and your task is to reverse it in-place—meaning you can’t use extra space beyond a few variables. For example, with s = ["h","e","l","l","o"]
, you modify it to ["o","l","l","e","h"]
. This problem tests your ability to manipulate arrays efficiently, connecting to basic concepts in Python Basics and preparing you for more complex problems like LeetCode 541: Reverse String II.
Problem Statement
- Input: A character array s.
- Output: None (modify s in-place to reverse it).
- Rules:
- Reverse the order of characters.
- Do not allocate extra space for another array (O(1) space complexity).
- Modify s directly.
Constraints
- 1 <= s.length <= 10⁵
- s[i] is a printable ASCII character.
Examples
- Input: ["h","e","l","l","o"]
- Output: ["o","l","l","e","h"]
- Input: ["H","a","n","n","a","h"]
- Output: ["h","a","n","n","a","H"]
- Input: ["a"]
- Output: ["a"]
Understanding the Problem: Flipping the String
To solve LeetCode 344: Reverse String in Python, we need to reverse the character array s
in-place, swapping elements without using extra storage. A naive approach—creating a new array and copying back—is O(n) space, violating the constraint. Instead, we’ll use:
- Best Solution (Two-Pointer): O(n) time, O(1) space—fast and space-efficient.
- Alternative Solution (Recursive): O(n) time, O(n) space—clear but less optimal due to stack usage.
Let’s start with the two-pointer solution, explained in a beginner-friendly way.
Best Solution: Two-Pointer Approach
Why This Is the Best Solution
The two-pointer approach is the top choice for LeetCode 344 because it’s efficient—O(n) time, O(1) space—and straightforward, using two pointers to swap characters from the ends inward. It meets the in-place requirement perfectly, avoiding extra memory beyond a couple of variables. It’s like flipping a string with a simple dance move—smooth and quick!
How It Works
Think of this as a string flipper:
- Step 1: Set Pointers:
- left starts at 0 (beginning).
- right starts at len(s) - 1 (end).
- Step 2: Swap and Move:
- While left < right:
- Swap s[left] and s[right].
- Move left forward, right backward.
- Step 3: Stop When Done:
- When pointers meet, string is reversed.
- Step 4: Why It Works:
- Swaps outer pairs inward.
- In-place with no extra array.
It’s like mirroring the string step-by-step!
Step-by-Step Example
Example: s = ["h","e","l","l","o"]
- Init: left = 0, right = 4
- Step 1: Swap h ↔ o, s = ["o","e","l","l","h"], left = 1, right = 3
- Step 2: Swap e ↔ l, s = ["o","l","l","e","h"], left = 2, right = 2
- Step 3: left ≥ right, stop
- Result: ["o","l","l","e","h"]
Example: s = ["H","a","n"]
- Init: left = 0, right = 2
- Step 1: Swap H ↔ n, s = ["n","a","H"], left = 1, right = 1
- Step 2: left ≥ right, stop
- Result: ["n","a","H"]
Code with Detailed Line-by-Line Explanation
class Solution:
def reverseString(self, s: List[str]) -> None:
# Set two pointers
left, right = 0, len(s) - 1
# Swap characters while pointers don’t meet
while left < right:
s[left], s[right] = s[right], s[left] # Swap
left += 1
right -= 1
# No return, s is modified in-place
- Line 3: Initialize left at start, right at end.
- Lines 6-9: While loop:
- Swap characters at left and right.
- Move pointers inward.
- Time Complexity: O(n)—traverse half the array.
- Space Complexity: O(1)—only two pointers.
This is like a string-flipping maestro—fast and sleek!
Alternative Solution: Recursive Approach
Why an Alternative Approach?
The recursive approach—O(n) time, O(n) space—reverses the string by swapping outer characters and recursing on the inner substring. It’s more intuitive for understanding recursion but uses O(n) stack space, violating the in-place constraint strictly. It’s like flipping the string layer-by-layer—clear but less optimal!
How It Works
Recurse and swap:
- Step 1: Base case: if length ≤ 1, do nothing.
- Step 2: Swap first and last characters.
- Step 3: Recurse on substring excluding ends.
Step-by-Step Example
Example: s = ["h","e","l","l","o"]
- Call(0, 4): Swap h ↔ o, s = ["o","e","l","l","h"]
- Call(1, 3): Swap e ↔ l, s = ["o","l","l","e","h"]
- Call(2, 2): Base case, stop
- Result: ["o","l","l","e","h"]
Code for Recursive Approach
class Solution:
def reverseString(self, s: List[str]) -> None:
def recurse(left, right):
if left >= right:
return
s[left], s[right] = s[right], s[left]
recurse(left + 1, right - 1)
recurse(0, len(s) - 1)
- Time Complexity: O(n)—recursive calls halve the problem.
- Space Complexity: O(n)—recursion stack.
It’s a recursive flipper—vivid but heavy!
Comparing the Two Solutions
- Two-Pointer (Best):
- Pros: O(n) time, O(1) space, in-place and fast.
- Cons: Iterative logic.
- Recursive (Alternative):
- Pros: O(n) time, O(n) space, elegant recursion.
- Cons: Stack space violates O(1) constraint.
Two-pointer wins for efficiency and rules.
Additional Examples and Edge Cases
- ["a"]: ["a"].
- []: [] (not per constraint, but handled).
- ["a","b"]: ["b","a"].
Both work, but two-pointer is optimal.
Complexity Breakdown
- Two-Pointer: Time O(n), Space O(1).
- Recursive: Time O(n), Space O(n).
Two-pointer is the clear choice.
Key Takeaways
- Two-Pointer: Flip in place—efficient!
- Recursive: Flip with depth—clear!
- Python: Arrays and swaps shine—see [Python Basics](/python/basics).
- Reversal: Pointers beat recursion here.
Final Thoughts: Flip the String
LeetCode 344: Reverse String in Python is a foundational array challenge. The two-pointer solution offers speed and elegance, while recursion provides a recursive lens. Want more string fun? Try LeetCode 541: Reverse String II or LeetCode 151: Reverse Words in a String. Ready to reverse? Head to Solve LeetCode 344 on LeetCode and flip that string today!