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 only out of sequence number from an array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers. The array is sorted in ascending order and only one element in the array is out of order.
Our function should find and return that element.
Approach
The solution works by checking each element against its neighbors. When we find an element that is greater than the next element AND the next element is also greater than the element after it, we've found our out-of-sequence number.
Example
Following is the code:
const arr = [1, 2, 3, 4, 17, 5, 6, 7, 8];
const findWrongNumber = (arr = []) => {
for(let i = 0; i < arr.length - 1; i++){
const el = arr[i];
if(el - arr[i + 1] < 0 && arr[i + 1] - arr[i + 2] > 0){
return arr[i + 1];
}
}
};
console.log(findWrongNumber(arr));
17
How It Works
The algorithm examines each element and checks two conditions:
-
el - arr[i + 1] < 0- Current element is less than the next element (normal ascending order) -
arr[i + 1] - arr[i + 2] > 0- Next element is greater than the element after it (breaks ascending order)
When both conditions are true, the element at position i + 1 is the out-of-sequence number.
Alternative Approach
Here's another method that finds the element by detecting the first break in sequence:
const arr2 = [1, 2, 3, 4, 17, 5, 6, 7, 8];
const findWrongNumberAlt = (arr = []) => {
for(let i = 0; i < arr.length - 1; i++){
if(arr[i] > arr[i + 1]){
return arr[i];
}
}
};
console.log(findWrongNumberAlt(arr2));
17
Edge Cases
Let's test with different scenarios:
// Out of sequence at the beginning
const arr3 = [10, 1, 2, 3, 4];
console.log("Beginning:", findWrongNumberAlt(arr3));
// Out of sequence at the end
const arr4 = [1, 2, 3, 4, 2];
console.log("End:", findWrongNumberAlt(arr4));
Beginning: 10 End: 4
Conclusion
Both approaches effectively find the out-of-sequence element by detecting breaks in the ascending order. The first method is more specific, while the alternative approach is simpler and works for most cases where the wrong element appears before its correct position.
