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
Finding special array - JavaScript
An array is a special array if:
- All the elements at odd indices are odd - All the elements at even indices are even
We need to write a JavaScript function that takes an array and checks if it's a special array or not.
Understanding the Logic
For an array to be special:
- Index 0 (even): element must be even
- Index 1 (odd): element must be odd
- Index 2 (even): element must be even
- Index 3 (odd): element must be odd
The key insight is that arr[i] % 2 should equal i % 2 for all indices.
Example
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const isSpecial = (arr = []) => {
for(let i = 0; i < arr.length; i++){
if(arr[i] % 2 === i % 2){
continue;
}
return false;
}
return true;
};
console.log(isSpecial(arr));
true
Testing with Different Arrays
// Test case 1: Special array console.log(isSpecial([2, 3, 4, 5])); // true // Test case 2: Not special array console.log(isSpecial([1, 2, 3, 4])); // false (1 at even index) // Test case 3: Empty array console.log(isSpecial([])); // true (vacuously true) // Test case 4: Single element arrays console.log(isSpecial([4])); // true (even at index 0) console.log(isSpecial([3])); // false (odd at index 0)
true false true true false
Alternative Implementation
Here's a more concise version using the every() method:
const isSpecialArray = (arr) => {
return arr.every((element, index) => element % 2 === index % 2);
};
console.log(isSpecialArray([0, 1, 2, 3, 4, 5])); // true
console.log(isSpecialArray([1, 0, 3, 2])); // false
true false
How It Works
The function checks each element's parity (even/odd) against its index's parity:
-
element % 2returns 0 for even numbers, 1 for odd numbers -
index % 2returns 0 for even indices, 1 for odd indices - If they match for all elements, the array is special
Conclusion
A special array requires elements and indices to have matching parity. The solution efficiently checks this condition using modulo operations and early termination for better performance.
Advertisements
