
Coding Interview Question to write method which Reverses Array in place.
You have given an array of integers and your task is to reverse the array. This is an easy coding challenge and you mostly will be asked during Phone Screening.
Read More:
First you can easily think of creating another empty array and push all the elements from last index to first.
Here is the pseudo code.
for (let i = arr.length; i > = 0 ; i–) {
new arr.push(arr[i]);
}
But we are using two arrays which is not full-filling condition of in place and also using more memory space which is not efficient solution either.
Instead of creating new array, we can create temporary variable which can be updated with new value and assign that to current element to reverse array in place.
Here is the pseudo code for that.
for (let i = 0; i < arr.length/2; i++) {
temp = arr[i];
arr[i] = arr[arr.length – 1 -i];
arr[arr.length – 1 – i] = temp;
}
Now we can use this pseudo code in working solution.
const reverseArr = (arr) => {
let temp = 0;
for (let i = 0; i < arr.length/2; i++) {
temp = arr[i];
arr[i] = arr[arr.length - 1 -i];
arr[arr.length - 1 - i] = temp;
}
return arr;
}
const arr = [3, 5, 6, 2, 4, 7];
//4,2,6,5,3
console.log(reverseArr(arr));
You can use this code playground to run the working solution with different inputs.
Look Out for the Open Positions: https://www.simplyhired.com/