[Easy] 344. Reverse String
Reverse the array of characters s in-place using O(1) extra memory.
Pattern: Two Pointers · Template: Arrays & Strings
Examples
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints
1 <= s.length <= 10^5s[i]is a printable ASCII character
Common Approaches
Typical techniques for this pattern:
| Approach | Time | Space | Notes |
|---|---|---|---|
| Opposite ends (this problem) | O(n) | O(1) | Sorted array pair search, reversal |
| Slow / fast pointers | O(n) | O(1) | Linked list middle, cycle detection |
| Same-direction chase | O(n) | O(1) | Remove duplicates in-place |
| Sliding window (variable) | O(n) | O(1) | Subarray with constraint |
Thinking Process
In-place reversal is a classic two-pointer pattern: swap the characters at the ends, then move inward until the pointers meet.
leftstarts at 0,rightatn - 1- While
left < right, swaps[left]ands[right], then incrementleftand decrementright - No extra array needed — each swap fixes two positions
Solution — O(n) time, O(1) space
class Solution:
def reverseString(self, s: list[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
Solution Explanation
Approach: Opposite ends (this problem)
Key idea: In-place reversal is a classic two-pointer pattern: swap the characters at the ends, then move inward until the pointers meet.
How the code works:
leftstarts at 0,rightatn - 1- While
left < right, swaps[left]ands[right], then incrementleftand decrementright - No extra array needed — each swap fixes two positions
Walkthrough — input s = ["h","e","l","l","o"], expected output ["o","l","l","e","h"]:
- Initialize variables from the problem setup.
- Apply the main loop / recursion until the condition is met.
- Confirm the result matches the expected output.
Time: O(n) · Space: O(1)
Common Mistakes
- Using
left <= rightand swapping the middle element twice (useleft < right) - Allocating a second array — violates the in-place constraint
- Forgetting that
sis modified in place (return type isvoid)
Key Takeaways
- Opposite-end two pointers is the standard template for in-place reversal (arrays, strings, linked lists)
- Same idea extends to LC 345. Reverse Vowels of a String and partial reversals like LC 541. Reverse String II
Related Problems
References
- LC 344: Reverse String on LeetCode
- LeetCode Discuss — LC 344: Reverse String
- LeetCode Editorial (may require premium)