๐งฉ Problem Statement
Write a function that reverses a string. The input string is given as a character array s
, and you must reverse it in-place with O(1) extra memory.
๐ข Example
python
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
โ
Constraints
1 <= s.length <= 10โต
s[i]
is a printable ASCII character.
- Must be done in-place (i.e., modify the original array, not return a new one).
๐ก Key Concept: Two-Pointer Swapping
This is a classic two-pointer problem, often used to reverse arrays or strings. The idea is simple:
- Initialize two pointers,
left = 0
and right = len(s) - 1
- Swap
s[left]
with s[right]
- Move both pointers toward the center
- Repeat until they meet or cross
โ
Python Code โ Two-Pointer Method (In-place)
python
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
๐ง Note: Since this is done in-place, there is no return
statement. The original array s
is directly modified.
๐ Step-by-Step Example
For s = ["h", "e", "l", "l", "o"]
:
StepLeftRights104["o", "e", "l", "l", "h"]
213["o", "l", "l", "e", "h"]
322Pointers meet โ done!
๐งช Alternative: Pythonic One-liner (Not allowed in interviews where in-place is required)
python
s[:] = s[::-1] # This also modifies the list in-place
But this uses slicing and may not be accepted in all interview scenarios.
โฑ๏ธ Time and Space Complexity
MetricValueTime ComplexityO(n)Space ComplexityO(1)
Since you only use a few pointers and swap elements directly, space remains constant.
๐ฆ Extra Test Cases
python
Input: ["A"] โ Output: ["A"]
Input: ["a", "b"] โ Output: ["b", "a"]
Input: ["1","2","3","4"] โ Output: ["4","3","2","1"]
๐ Use Cases
- Reversing strings in-place in embedded systems
- Data cleaning pipelines
- UI text rendering in reverse languages (RTL)
โ
Conclusion
LeetCode 344: Reverse String is a great entry-level problem to understand in-place operations and the two-pointer pattern. It builds the foundation for more complex tasks like reversing substrings, linked lists, or even matrix diagonals.