easy

Reverse String

Reverse an array of characters in place.

1. Define the problem

Reverse String

Write a function that reverses an array of characters in place . Use two pointers starting at the left and right ends of the array, swapping the characters they point to and converging toward the middle until they meet.

Constraints

  • 1 ≤ s.length ≤ 105
  • si is a printable ASCII character

Example

Inputs = ['h', 'e', 'l', 'l', 'o']
Output['o', 'l', 'l', 'e', 'h']

Explanation Swapping characters from both ends inward reverses the array to "olleh".

2. Know the words first

In plain terms

In place
Making the change directly inside the given array instead of building a new one, using little to no extra memory.
3. Visualize the solution

Swap from both ends, converge toward the middle

Swap from both ends, converge toward the middle
Statusinit

left=0 ('h') and right=4 ('o') are about to swap.

What happens in this step

left = 0 (value 'h'), right = 4 (value 'o')

The values at the two ends are about to be swapped.
Step 1 of 4

Steps to visualize

  1. Place one pointer at the start and one at the end of the array.
  2. Swap the characters at the two pointers.
  3. Move the left pointer right and the right pointer left.
  4. Repeat until the pointers meet or cross.
  5. The array is now reversed in place.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Swap from both ends, converge toward the middle
Statusinit

left=0 ('h') and right=4 ('o') are about to swap.

What happens in this step

left = 0 (value 'h'), right = 4 (value 'o')

The values at the two ends are about to be swapped.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function reverseString(s) {
  let left = 0;
  let right = s.length - 1;

  while (left < right) {
    const temp = s[left];
    s[left] = s[right];
    s[right] = temp;
    left++;
    right--;
  }

  return s;
}
Time
O(n)
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
s = ['h', 'e', 'l', 'l', 'o']['o', 'l', 'l', 'e', 'h']example from the docstring
s = ['a']['a']smallest valid input, a single character
s = ['a', 'b', 'c', 'd']['d', 'c', 'b', 'a']even-length array, no middle character
s = ['a', 'b']['b', 'a']boundary case, exactly two elements
s = ['x', 'x']['x', 'x']identical characters, no visible change after reversing
s = ['a', 'b', 'c']['c', 'b', 'a']odd-length array with a middle character left untouched