How to useHashing in Javascript
- Create an array temp[] of size N + 1 (where N is the length of array) with all initial values as 0.
- Traverse the input array arr[], and set the temp index frequency to 1, i.e. if(temp[arr[i]] == 0) temp[arr[i]] = 1
- Traverse temp[] and output the array element having value as 0 (This is the missing element).
Example:
// Function to find the missing number
function findMissing(arr, N) {
let i;
// Create an Array of size N
// and filled with 0
let temp = new Array(N).fill(0);
// If array element exist then
// set the frequency to 1
for (i = 0; i < N; i++) {
temp[arr[i] - 1] = 1;
}
let ans = 0;
for (i = 0; i <= N; i++) {
if (temp[i] === 0)
ans = i + 1;
}
console.log(ans);
}
// Driver code
let arr = [1, 3, 7, 5, 6, 2];
let n = arr.length;
// Function call
findMissing(arr, n);
Output
4
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