LeetCode 344. Reverse String — JavaScript Basics

This week I will solve problem 344 on LeetCode called Reverse String. Below is my implementation of the problem.

The Description

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

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

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

Example 2:

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

My Solution

var reverseString = function(s) {
for (let i = 0; i < s.length/2; i++) {
let n = s[i]
s[i] = s[s.length-i-1]
s[s.length-i-1] = n
}
};

This solution will use a for loop to iterate the string all the way to the middle and swap the left side character with the right character. This solution will give us a solution but is not the most efficient method of solving the problem with a runtime of 100s and 42.8 mb of memory used.

--

--