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
Can array form consecutive sequence - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and checks if the elements of the array can be rearranged to form a sequence of consecutive numbers or not.
For example, if we have an array [3, 1, 4, 2, 5], these numbers can be rearranged as [1, 2, 3, 4, 5] to form a consecutive sequence.
Problem Understanding
A consecutive sequence means each number is exactly 1 more than the previous number. To check this, we need to:
- Sort the array in ascending order
- Verify each element is exactly 1 more than the previous element
- Handle edge cases like empty arrays or single elements
Example Input and Expected Output
If the array is:
const arr = [3, 1, 4, 2, 5];
Then the output should be:
true
Implementation
Here's the complete solution:
const arr = [3, 1, 4, 2, 5];
const canBeConsecutive = (arr = []) => {
if (!arr.length) {
return false;
}
const copy = arr.slice();
copy.sort((a, b) => a - b);
for (let i = copy[0], j = 0; j
true
How It Works
The function follows these steps:
-
Edge Case: Returns
false for empty arrays
-
Create Copy: Uses
slice() to avoid modifying the original array
-
Sort: Arranges numbers in ascending order
-
Check Sequence: Starting from the first element, verifies each subsequent element is exactly 1 more
Testing with Different Cases
const canBeConsecutive = (arr = []) => {
if (!arr.length) {
return false;
}
const copy = arr.slice();
copy.sort((a, b) => a - b);
for (let i = copy[0], j = 0; j
true
false
true
false
true
Key Points
- Single-element arrays return
true(trivially consecutive) - Empty arrays return
falseby design choice - The algorithm has O(n log n) time complexity due to sorting
- Space complexity is O(n) for creating the copy
Conclusion
This solution efficiently checks if an array can form a consecutive sequence by sorting first, then verifying each element follows the consecutive pattern. The approach handles various edge cases and works for arrays of any size.
