This content originally appeared on DEV Community and was authored by nikhilkalariya
with using sort method to solve
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);
Without using any built in method
//third way to find missng number
function getMissingNo(arr1, n) {
// The range is [1, N]
const N = n + 1;
// Calculate the sum of the range
const totalSum = (N * (N + 1)) / 2;
// Sum of elements in the array
let arraySum = 0;
for (let i = 0; i < n; i++) {
arraySum += arr1[i];
}
// The missing number
return totalSum - arraySum;
}
// Driver code
const arr1 = [1, 2, 3, 5];
const N = arr.length;
console.log(getMissingNo(arr1, N));
With using reduce method to solve
//second way find missing job
function findMissingNumber(arr) {
// Calculate the length of the array + 1 (since one number is missing)
const n = arr.length + 1;
// Calculate the expected sum of numbers from 1 to n
const expectedSum = (n * (n + 1)) / 2;
// Calculate the sum of numbers in the given array
const actualSum = arr.reduce((acc, num) => acc + num, 0);
// The difference between expectedSum and actualSum is the missing number
const missingNumber = expectedSum - actualSum;
console.log("The missing number is:", missingNumber);
return missingNumber;
}
// Example usage
const arr = [1, 2, 4, 5, 6];
findMissingNumber(arr); // Output will be: The missing number is: 3
This content originally appeared on DEV Community and was authored by nikhilkalariya
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
nikhilkalariya | Sciencx (2024-06-27T09:18:41+00:00) Missing Number. Retrieved from https://www.scien.cx/2024/06/27/missing-number/
" » Missing Number." nikhilkalariya | Sciencx - Thursday June 27, 2024, https://www.scien.cx/2024/06/27/missing-number/
HARVARDnikhilkalariya | Sciencx Thursday June 27, 2024 » Missing Number., viewed ,<https://www.scien.cx/2024/06/27/missing-number/>
VANCOUVERnikhilkalariya | Sciencx - » Missing Number. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/27/missing-number/
CHICAGO" » Missing Number." nikhilkalariya | Sciencx - Accessed . https://www.scien.cx/2024/06/27/missing-number/
IEEE" » Missing Number." nikhilkalariya | Sciencx [Online]. Available: https://www.scien.cx/2024/06/27/missing-number/. [Accessed: ]
rf:citation » Missing Number | nikhilkalariya | Sciencx | https://www.scien.cx/2024/06/27/missing-number/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.