Solution for array reverse algorithm problem JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
]
raja
Published on 24-Aug-2020 12:25:45
Advertisements