How to use two pointer In Javascript
In this approach we use two pointers, one at the start and one at the end of the array. then we use a while loop to iterate until the pointers meet. We compare elements at the pointers and move them towards each other. If at any point, the elements are not equal means array is not palindrome.
Example: The below example uses two pointer approach to check if an array is palindrome or not.
function isPalindrome(arr) {
let start = 0;
let end = arr.length - 1;
while (start < end) {
if (arr[start] !== arr[end]) {
return 'Not palindrome';
}
start++;
end--;
}
return 'Palindrome';
}
const array1 = [1, 2, 3, 2, 1];
console.log(isPalindrome(array1));
Output
Palindrome
JavaScript Program to Check if an Array is Palindrome or Not
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if an array is a palindrome, compare it to its reverse version. If they match, it’s a palindrome.
Given an array, the task is to determine whether an array is a palindrome.
Examples:
Input: arr = [3, 6, 0, 6, 3]
Output: Palindrome
Input: arr = [1, 2, 3, 4, 5]
Output: Not Palindrome
Below are the approaches to checking if an array is palindrome or not.
Table of Content
- Using Array Reversal
- Using Iteration
- Using two pointer
- Using Array.every() Method: