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
Checking if two arrays can form a sequence - JavaScript
We are required to write a JavaScript function that takes in two arrays of numbers.
And the function should return true if the two arrays upon combining and shuffling can form a consecutive sequence, false otherwise.
For example ? If the arrays are ?
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
Then the output should be true because when combined and sorted, they form: [1, 2, 3, 4, 5, 6, 7, 8, 9] which is a consecutive sequence.
Example
Following is the code ?
const arr1 = [4, 6, 2, 9, 3];
const arr2 = [1, 5, 8, 7];
const canFormSequence = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
if(combined.length < 2){
return true;
}
combined.sort((a, b) => a - b);
// Check if each consecutive pair differs by 1
for(let i = 0; i < combined.length - 1; i++){
if(combined[i + 1] - combined[i] !== 1){
return false;
}
}
return true;
};
console.log(canFormSequence(arr1, arr2));
Output
true
How It Works
The function combines both arrays using the spread operator, sorts the combined array in ascending order, then checks if each consecutive pair of numbers differs by exactly 1. If any pair has a difference other than 1, it returns false.
Testing with Different Examples
// Test case 1: Valid consecutive sequence
const test1_arr1 = [1, 3, 5];
const test1_arr2 = [2, 4];
console.log("Test 1:", canFormSequence(test1_arr1, test1_arr2)); // true
// Test case 2: Invalid sequence with gap
const test2_arr1 = [1, 3, 7];
const test2_arr2 = [2, 4];
console.log("Test 2:", canFormSequence(test2_arr1, test2_arr2)); // false
// Test case 3: Single array
const test3_arr1 = [5];
const test3_arr2 = [];
console.log("Test 3:", canFormSequence(test3_arr1, test3_arr2)); // true
Test 1: true Test 2: false Test 3: true
Conclusion
This function efficiently determines if two arrays can form a consecutive sequence by combining, sorting, and checking for unit differences between adjacent elements. It handles edge cases like empty arrays and single elements correctly.
