Algorithm


Problem Name: 344. Reverse String

Problem URL: https://leetcode.com/problems/reverse-string/

Level: Easy

Details:

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.

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:

 

Algorithm:

We can solve this Reverse String problem in several ways.

Method 1: Use javascript reverse() method to reverse any string.

array.reverse();

 

Method 2: Using forEach or for loop to solve the problem.

We can start the loop from end to start.

const reversed = [];
for(let i = s.length - 1; i >= 0; i--) {
    reversed.push(s[i]);
}

s.forEach((ch, i) => {
    s[i] = reversed[i];
});

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


var reverseString = function(s) {
    return s.reverse();
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
["h","e","l","l","o"]

Output

x
+
cmd
["o","l","l","e","h"]

#2 Using For Loop to solve Reverse problem in Javascript [Not tested]

Code - Javascript Programming


var reverseString = function(s) {
    const reversed = [];
    for(let i = s.length - 1; i >= 0; i--) {
    	reversed.push(s[i]);
    }

    s.forEach((ch, i) => {
        s[i] = reversed[i];
    });
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
["H","a","n","n","a","h"]

Output

x
+
cmd
["h","a","n","n","a","H"]

Demonstration


We'll just use string reverse() method of javascript.

Leetcode - 344. Reverse String Solution in Javascript Leetcode