Skip to main content

344. Reverse String

easy

Reverse a character array in-place. A warm-up problem — but stay alert for the in-place constraint and don't reach for the built-in reverse without thinking.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is a printable ASCII character.

Examples

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"]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Allocating a new reversed array works but breaks the O(1) extra memory rule.

Hint 2

Two pointers — one at each end — swapping toward the middle is the canonical approach.

Hint 3

Loop while left < right: swap s[left] and s[right]; advance left, retreat right.

Solution approach

Reveal approach

Two pointers. left = 0, right = n - 1. While left < right, swap s[left] and s[right], then advance left and retreat right. Stop when they meet (odd-length array — middle is its own reverse) or cross (even-length array). One half-pass through the array, O(n) time, O(1) extra space.

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • two-pointers

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft

Practice these live with InterviewChamp.AI

Drill Reverse String and Strings problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →