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
Check if the elements of the array can be rearranged to form a sequence of numbers or not in 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 numbers or not.
For example: If the array is ?
const arr = [3, 1, 4, 2, 5];
Then the output should be true because these numbers can be rearranged to form the consecutive sequence: 1, 2, 3, 4, 5.
Approach
To solve this problem, we need to:
- Sort the array in ascending order
- Check if each element is exactly one more than the previous element
- Return true if all elements form a consecutive sequence, false otherwise
Example
The code for this will be ?
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 < copy.length; i++, j++){
if(copy[j] === i){
continue;
};
return false;
};
return true;
};
console.log(canBeConsecutive(arr));
Output
The output in the console will be ?
true
Testing with Different Arrays
Let's test our function with various arrays to see how it behaves:
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 < copy.length; i++, j++){
if(copy[j] === i){
continue;
};
return false;
};
return true;
};
// Test cases
console.log("Array [3, 1, 4, 2, 5]:", canBeConsecutive([3, 1, 4, 2, 5]));
console.log("Array [1, 3, 5]:", canBeConsecutive([1, 3, 5]));
console.log("Array [10, 11, 12]:", canBeConsecutive([10, 11, 12]));
console.log("Array [1, 1, 2, 3]:", canBeConsecutive([1, 1, 2, 3]));
console.log("Empty array []:", canBeConsecutive([]));
Output
Array [3, 1, 4, 2, 5]: true Array [1, 3, 5]: false Array [10, 11, 12]: true Array [1, 1, 2, 3]: false Empty array []: false
How It Works
The function works by:
- First checking if the array is empty and returning false if so
- Creating a copy of the array to avoid modifying the original
- Sorting the copy in ascending order
- Iterating through the sorted array, comparing each element with the expected consecutive value
- If any element doesn't match the expected consecutive pattern, it returns false
- If all elements form a consecutive sequence, it returns true
Conclusion
This function efficiently determines if an array can form a consecutive sequence by sorting and checking each element. It handles edge cases like empty arrays and duplicate numbers correctly.
