How to useSorting in Javascript
- First we will sort the array in ascending order. Sorting will helps us identify the missing number because it allows us to easily find where the sequence breaks.
- Next we will iterate over the sorted array. For each element at index i, we compare it with i + 1. If they are not equal then i + 1 is the missing numbe.
function findMissingNumber(arr) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== i + 1) {
return i + 1;
}
}
return arr.length + 1;
}
const numbers = [1, 2, 3, 4, 5, 6, 8, 9, 10];
const missingNumber = findMissingNumber(numbers);
console.log("The missing number is:", missingNumber);
Output
The missing number is: 7
JavaScript Program to Find the Missing Number
Given an array of size N-1 with integers in the range of [1, N]. The task is to find the missing number from the first N integers. There are no duplicate elements allowed in the array.
Examples:
Input : arr = [1, 2, 3, 5]
Output : 4
Input : arr = [1, 4, 3, 2, 6, 5, 7, 10, 9]
Output : 8
Contact Us