Solution for array reverse algorithm problem JavaScript

We have a requirement that we have to write a function to reverse an array but without changing the index of a special character presents in an array, like below example −

If ‘#’ is that special character then, the following array,

[18,-4,'#',0,8,'#',5]

should return −

[5, 8, "#", 0, -4, "#", 18],

Here, numbers are reversed, excluding '#' which retained its index.

Let’s write the code for this.

We will use the two-pointer approach here, start and end pointing to the extreme left and extreme right of the array respectively.

If at any index we find the special character, we skip that index and continue iteration, and when we find an index pair at which there is no special character, we swap their values and we continue doing this while the start pointer is less than the right pointer.

Example

const arr = [18,-4,'#',0,8,'#',5];
const reverseArray = (arr, special) => {
let start = 0, end = arr.length - 1, temp;
while(start < end){
if(arr[start] === special){
start++;
continue;
};
if(arr[end] === special){
end--;
continue;
};
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
};
};
reverseArray(arr, '#');
console.log(arr);

Output

The output in the console will be −

[
5, 8, '#', 0, -4, '#', 18
]

Updated on: 24-Aug-2020

142 Views