
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Solution for Array Reverse Algorithm Problem in 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 ]