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
Finding the continuity of two arrays in JavaScript
We are required to write a JavaScript function that takes in two arrays of numbers. The function should return true if the two arrays upon combining 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];
When combined and sorted, these arrays form [1, 2, 3, 4, 5, 6, 7, 8, 9], which is a consecutive sequence. Therefore, the output should be true.
Understanding Consecutive Sequences
A consecutive sequence means each number is exactly 1 more than the previous number when arranged in ascending order. To check this, we need to:
- Combine both arrays into one
- Sort the combined array
- Check if each element differs by exactly 1 from the next
Implementation
const arr1 = [4, 6, 2, 9, 3];
const arr2 = [1, 5, 8, 7];
const canFormSequence = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
// Handle edge case: arrays with less than 2 elements
if (combined.length a - b);
// Check if each consecutive pair differs by 1
for (let i = 0; i
true
How It Works
The function works by:
-
Combining arrays: Uses spread operator to merge both arrays
-
Sorting: Arranges numbers in ascending order
-
Checking differences: Verifies each pair of consecutive numbers differs by exactly 1
Testing with Different Examples
// Example 1: Forms consecutive sequence
const test1 = canFormSequence([1, 3, 5], [2, 4]);
console.log("Test 1 (1,3,5 + 2,4):", test1);
// Example 2: Missing numbers - not consecutive
const test2 = canFormSequence([1, 3, 6], [2, 4]);
console.log("Test 2 (1,3,6 + 2,4):", test2);
// Example 3: Duplicate numbers - not consecutive
const test3 = canFormSequence([1, 2, 3], [3, 4, 5]);
console.log("Test 3 (duplicates):", test3);
Test 1 (1,3,5 + 2,4): true
Test 2 (1,3,6 + 2,4): false
Test 3 (duplicates): false
Key Points
- The function handles edge cases like arrays with fewer than 2 elements
- Sorting is essential to check consecutive order properly
- The algorithm has O(n log n) time complexity due to sorting
- Duplicate numbers will break the consecutive sequence
Conclusion
This solution efficiently determines if two arrays can form a consecutive sequence by combining, sorting, and checking differences. The approach works for any size arrays and handles edge cases appropriately.
