Using Object
Using an Object to track number’s presence, iterate through 1 to 100, and return the first missing number from the given array.
Syntax:
function missingNumber(arr) {
const numberObj = {};
//code
}
Example: In this example, the missingNumber function finds the first missing number from 1 to 100 in the given array integer using an object for tracking.
function missingNumber(arr) {
const numberObj = {};
for (const num of arr) {
numberObj[num] = true;
}
for (let i = 1; i <= 100; i++) {
if (!numberObj[i]) {
return i;
}
}
}
const integer = [1, 2, 3, 4,/* ... */, 99, 100];
const result = missingNumber(integer);
console.log("Missing number:", result);
Output
Missing number: 5
JavaScript Program to Find the Missing Number in a Given Integer Array of 1 to 100
In this article, we are going to find the missing number in a given integer array of 1 to 100 in JavaScript, Given an array [] of size 100 with integers in the range of [1, 100], There are no duplicate values in the array and no larger value than the size of the array. The task is to print that which is missing value in the array.
Let’s take an example:
Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, /* Missing number */,12, /* ... */, 100]; Size of an array is 100
Output: 11
Explanation: The missing number between 1 to 100 is 11
There are several methods that can be used to find the missing number in a given integer array of 1 to 100 in JavaScript, which are listed below:
Table of Content
- Approach 1: Using the Mathematical Formulae
- Approach 2: Using the array iteration
- Approach 3: Using Object
- Approach 4: Using Bit Manipulation (XOR)
We will explore all the above methods along with their basic implementation with the help of examples.