Reverse String — LeetCode 344 Python Solution

EasyTwo PointersString
Problem
#344
Reading time
2 min

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 - 1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview