Reverse a String

beginner
1,800 views1,320 solved
stringtwo-pointers

Problem Description

Write a function that reverses a string. The input string is given as an array of characters.

You must do this by modifying the input array in-place with O(1) extra memory.

Example:

Input: s = ["h","e","l","l","o"]

Output: ["o","l","l","e","h"]

Input: s = ["H","a","n","n","a","h"]

Output: ["h","a","n","n","a","H"]

Constraints:

- 1 <= s.length <= 10^5

- s[i] is a printable ASCII character.

JavaScriptPress Ctrl+Enter to run tests
Loading editor...

Test Cases

Test 1

Basic string

Input:[ [ "h", "e", "l", "l", "o" ] ]
Expected:[ "o", "l", "l", "e", "h" ]
Test 2

Palindrome name

Input:[ [ "H", "a", "n", "n", "a", "h" ] ]
Expected:[ "h", "a", "n", "n", "a", "H" ]
Test 3

Single character

Input:[ [ "a" ] ]
Expected:[ "a" ]
ASleekGeek - Beyond the Code. Building the Future.