344. Reverse String
easyReverse 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 Sam K., 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^5s[i] is a printable ASCII character.
Examples
Example 1
s = ["h","e","l","l","o"]["o","l","l","e","h"]Example 2
s = ["H","a","n","n","a","h"]["h","a","n","n","a","H"]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
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
- 151. Reverse Words in a String
- 541. Reverse String II
- 189. Rotate Array
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
More Strings practice problems
- 3. Longest Substring Without Repeating Characters
- 5. Longest Palindromic Substring
- 6. Zigzag Conversion
- 14. Longest Common Prefix
- 20. Valid Parentheses
- 28. Find the Index of the First Occurrence in a String
- 49. Group Anagrams
- 58. Length of Last Word