Reverse String — LeetCode 344 Python Solution
EasyTwo PointersString
- Problem
- #344
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Write a function that reverses a string. The input string is given as an array of characters s.
Example
- Input
- s = ["h","e","l","l","o"]
- Output
- ["o","l","l","e","h"]
Python solution
Python
class Solution:
def reverseString(self, s: List[str]) -> None:
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 344. Reverse String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 344. Reverse String?
- LeetCode 344. Reverse String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 344. Reverse String?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 344. Reverse String?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 344. Reverse String cover?
- LeetCode 344. Reverse String is tagged Two Pointers and String on LeetCode.