LeetCode ยท #344

Reverse String Solution

Write a function that reverses a string. The input is given as an array of characters s. Do it in-place with O(1) extra memory.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #344

๐Ÿ—๏ธ

Pattern

Two Pointers โ€” converge & swap

Write a function that reverses a string in-place. The input is given as a character array s. You must do this by modifying the input array directly with O(1) extra memory.

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โต โ€ข s[i] is a printable ASCII character โ€ข Must use O(1) extra memory
02
Section Two ยท Approach 1

Brute Force โ€” New Array O(n)

Create a new array, copy elements in reverse order, then copy back. Or use a stack: push all characters, then pop them back. Both use O(n) extra space.

Why we can do better
Problem: Both approaches allocate O(n) extra memory. Reversing in-place only requires swapping elements from opposite ends โ€” no extra storage beyond a single temporary variable.
Java โ€” Stack-based (O(n) space)
import java.util.Stack; class Solution { public void reverseString(char[] s) { Stack<Character> stack = new Stack<>(); for (char c : s) stack.push(c); for (int i = 0; i < s.length; i++) s[i] = stack.pop(); } }
Python โ€” Slice (O(n) space)
class Solution: def reverseString(self, s: list[str]) -> None: s[:] = s[::-1] # creates a reversed copy internally
MetricValue
TimeO(n)
SpaceO(n) โ€” violates O(1) constraint
03
Section Three ยท Approach 2

Two Pointers โ€” O(n) time, O(1) space

Place one pointer at position 0 and one at position nโˆ’1. Swap the characters at both pointers, then move them inward. Repeat until they meet in the middle.

๐Ÿ’ก Mental model: Two people stand at opposite ends of a row of cards. They simultaneously pick up their cards, swap them, step inward, and repeat. After n/2 swaps, the entire row is reversed.
Algorithm
  • Step 1: Set left = 0, right = n - 1.
  • Step 2: While left < right: swap s[left] and s[right].
  • Step 3: left++, right--.
  • Step 4: When pointers cross โ†’ done. Array is reversed.
๐ŸŽฏ When to recognize this pattern:
  • Any in-place transformation that pairs the first element with the last, second with second-to-last, etc. โ€” use converging two pointers.
  • This is the simplest and most fundamental two-pointer pattern.
  • It appears in reversals, palindrome checks, and partitioning problems.
04
Section Four ยท Trace

Visual Walkthrough

Trace through s = ['h', 'e', 'l', 'l', 'o']:

Two Pointers โ€” swap from both ends
INITIAL h e l l o L=0 R=4 Swap 1: L=0, R=4 โ†’ swap 'h' โ†” 'o' โ†’ [o, e, l, l, h] Swap 2: L=1, R=3 โ†’ swap 'e' โ†” 'l' โ†’ [o, l, l, e, h] L=2, R=2 โ†’ pointers meet at middle 'l' โ†’ DONE RESULT o l l e h Answer: ['o','l','l','e','h'] โœ“
Notice:
  • Only โŒŠn/2โŒ‹ = 2 swaps needed for a 5-element array. The middle element stays in place.
  • For even-length arrays, all elements get swapped.
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Two Pointers
class Solution { public void reverseString(char[] s) { int left = 0, right = s.length - 1; while (left < right) { char temp = s[left]; s[left] = s[right]; s[right] = temp; left++; right--; } } }
Python โ€” Two Pointers
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
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceTrade-off
Stack / New ArrayO(n)O(n)Violates O(1) space constraint
Two Pointers โ† optimal O(n) O(1) n/2 swaps, one temp variable
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Single character['a']left == right immediately โ€” no swaps, array unchanged.
Two characters['a', 'b']One swap โ†’ ['b', 'a']. Minimum case that actually reverses.
Palindrome['a', 'b', 'a']Reversal produces the same array. Swaps still execute, just swap same values.
Even length['a', 'b', 'c', 'd']n/2 = 2 swaps. No middle element left alone.
Odd length['a', 'b', 'c']Middle element 'b' stays. Pointers cross there.
โš  Common Mistake: Using left <= right instead of left < right. When left equals right, swapping an element with itself is harmless but unnecessary. The correct condition is left < right โ€” stop when pointers meet or cross.

โ† Back to Two Pointers problems