Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Checking for special type of Arrays in JavaScript
We are required to write a JavaScript function that takes in an array of literals and checks if elements are the same or not if read from front or back. Such arrays are also known by the name of palindrome arrays.
Some examples of palindrome arrays are:
const arr1 = ['a', 'b', 'c', 'b', 'a']; const arr2 = [4, 7, 7, 4]; const arr3 = [7, 7, 7, 7, 7, 7];
Method 1: Using a For Loop
This approach compares elements from both ends moving towards the center:
const arr = [1, 5, 7, 4, 15, 4, 7, 5, 1];
const isPalindrome = arr => {
const { length: l } = arr;
const mid = Math.floor(l / 2);
for(let i = 0; i
true
false
true
Method 2: Using Array.reverse() and join()
This method converts the array to string and compares it with its reversed version:
const isPalindromeReverse = arr => {
return arr.join(',') === arr.slice().reverse().join(',');
};
const testArray1 = [1, 2, 3, 2, 1];
const testArray2 = [1, 2, 3, 4, 5];
console.log(isPalindromeReverse(testArray1));
console.log(isPalindromeReverse(testArray2));
true
false
Method 3: Using Two Pointers
This efficient approach uses two pointers moving from opposite ends:
const isPalindromeTwoPointers = arr => {
let left = 0;
let right = arr.length - 1;
while (left
true
false
true
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| For Loop | O(n/2) | O(1) | Good |
| Array.reverse() | O(n) | O(n) | High |
| Two Pointers | O(n/2) | O(1) | High |
Conclusion
The two-pointer approach offers the best combination of efficiency and readability for checking palindrome arrays. It uses constant space and only needs to iterate through half the array elements.
Advertisements
