Interview Question – Write a function that Reverses a String.

In many Technical Interview, you may get asked easy to hard coding challenge which you need to solve efficiently. Most of the questions are easy to navigate.

In this post we are talking about coding challenge about data structure array and how to solve challenge inplace without using additional space and with O(N) time complexity.

Here is the coding question.

Question: Write a function that reverses a string.

Description: 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"]

Now, to solve this problem we know if we use another array we can easily reverse the string.

For Example:

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

But, here we are adding extra space which is not efficient solution.

We can use temporary variable which holds value and we can reverse array in place. We can call it swap values in place.

const reversString = (s) => {
let tmp = '';
for (let i = 0; i < s.length; i++) {
tmp = s[i];
s[i] = s[s.length - 1 - i];
s[s.length - 1 - i] = tmp;
}
return s;
}

To improve this code we can use constant for character array length.

const reversString = (s) => {
let tmp = '';
const len = s.length;
for (let i = 0; i < len/2; i++) {
tmp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = tmp;
}
return s;
}