Missing Number
nikhilkalariya
Posted on June 27, 2024
with using sort method to solve
const numbers = [1, 2, 3, 4, 5, 6, 8, 9, 10];
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 missingNumber = findMissingNumber(numbers);
console.log("The missing number is:", missingNumber);
Missing number using for loop
function test(nums) {
for (let n = 1; n<= nums.length + 1; n++) {
if (nums.indexOf(n) === -1)
return n;
}
}
nums = [1,3,5,6,7]
console.log("nums = "+nums)
console.log("Missing number of the said array: "+test(nums));
Without using any built in method
//third way to find missng number
const arr1 = [1, 2, 3, 5];
const N = arr1.length;
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
console.log(getMissingNo(arr1, N));
With using reduce method to solve
const arr = [1, 2, 4, 5, 6];
//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
findMissingNumber(arr); // Output will be: The missing number is: 3
Find all missing first to last element between
const arr1 = [1, 3, 5, 7];
// Find the minimum and maximum values in the array
const min = Math.min(...arr1);
const max = Math.max(...arr1);
// Initialize an array to hold the missing numbers
const missingNumbers = [];
// Loop through the range from min to max
for (let i = min; i <= max; i++) {
// If the current number is not in the array, add it to the missing numbers
if (!arr1.includes(i)) {
missingNumbers.push(i);
}
}
console.log(missingNumbers);
💖 💪 🙅 🚩
nikhilkalariya
Posted on June 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.