#344

Reverse String

Easy
Two PointersStringTwo PointersArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using the two-pointer technique allows us to reverse the string in-place without needing extra space for a new string. This is efficient and meets the problem's constraints.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, one at the start (left) and one at the end (right) of the array.
  2. 2Step 2: Swap the characters at the left and right pointers.
  3. 3Step 3: Move the left pointer one step to the right and the right pointer one step to the left.
  4. 4Step 4: Repeat until the left pointer is greater than or equal to the right pointer.
solution.py6 lines
1def reverseString(s):
2    left, right = 0, len(s) - 1
3    while left < right:
4        s[left], s[right] = s[right], s[left]
5        left += 1
6        right -= 1

Complexity note: The time complexity is O(n) because we only traverse the string once. The space complexity is O(1) since we are reversing the string in-place without using extra space.

  • 1Using in-place operations saves memory and is often required in interviews.
  • 2The two-pointer technique is a common pattern for problems involving arrays or strings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.