Open In App

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 or not.

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.

Using Array Reversal

In this approach, we are using array reversal to create a reversed copy of the original array, then comparing both arrays' string representations to determine if the array is a palindrome or not.

Example: The below example uses Array Reversal to check if an array is palindrome or not.

let arr = [1, 2, 3, 4, 5, 6];
let reversedArr = [...arr].reverse();
let res = JSON.stringify(arr) === 
   JSON.stringify(reversedArr) ? "Palindrome" : "Not Palindrome";
console.log(res);

Output
Not Palindrome

Time Complexity: O(n), where n is the number of elements in the array.

Space Complexity: O(n)

Using Iteration

In this approach, we are using iteration with two pointers starting from both ends towards the middle of the array, comparing corresponding elements to determine if the array is a palindrome or not.

Example: The below example uses Iteration to check if an array is palindrome or not.

let arr = [3, 6, 0, 6, 3];
let res = "Palindrome";
for (let i = 0; i < arr.length / 2; i++) {
    if (arr[i] !== arr[arr.length - 1 - i])
    {
        res = "Not Palindrome";
        break;
    }
}
console.log(res);

Output
Palindrome

Time Complexity: O(n/2) = O(n), where n is the number of elements in the array.

Space Complexity: O(1)

Using two pointer

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
Article Tags :