Reverse String in JavaScript, LeetCode
I’m going to walk through a JavaScript solution to the Reverse String question from LeetCode’s Top Interview Questions (Easy Collection).
Here is the question from LeetCode:
I’m not sure why the question is posed as a string reversal when the input is already an array but here we go…
This is my solution, which has a runtime of 199ms (beats 9.95% of JS solutions) and memory usage of 46.1MB (beats 67% of JS solutions). I toyed with having a variable halfLength for the loop, which sometimes lowered memory usage significantly but also increased runtime. I get different numbers every time I submit a LeetCode solution so it’s basically a toss up and I went with a cleaner version without the variable.
I went ahead and checked the hint LeetCode provides before starting and used an opposite directional two-pointer approach. The question is much like their first one in the Arrays section (https://medium.com/@kajohnson3140/remove-duplicates-from-sorted-array-939fdf6965a6) in the same collection so the answer is similar.
Get K. Johnson’s stories in your inbox
Join Medium for free to get updates from this writer.
I first set a variable last to hold a pointer to the last index in the array. I then wrote a loop to start at the beginning of the array and stop in the middle of the array. The variable first holds the value at the beginning of the array that we want to swap with the corresponding value at the end of the array. I then make the swap and decrement last.
Walking through the example input [“h”, “e”, “l”, “l”, “o”]…
- last is set to 4 (s[4] value “o”) and the loop starting i at index 0, first is set to value “h”, s[0] is set to s[last] which makes the first value “o” and s[last] is set to first which makes the last value “h”, last is decremented to 3
- s now looks like [“o”, “e”, “l”, “l”, “h”]
- last is now at 3 (s[3] value “l”) and the loop increments i to index 1, first is set to value “e”, s[1] is set to s[last] which makes the first value “l” and s[last] is set to first which makes the last value “e”, last is decremented to 2
- s now looks like [“o”, “l”, “l”, “e”, “h”]
- the loop continues but the indexes are the same so it does swap the middle “l” with itself, exits the loop, and returns the array.
If I were to improve the function I would make the loop stop before the middle of an odd numbered string/array.
Questions, contributions welcomed! ty!








