Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.
home / developersection / forums / given an array of non-duplicating numbers from 1 to n where one number is missing, find it.
Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.
Aryan Kumar
28-Apr-2023o find the missing number in an array of non-duplicating numbers from 1 to n, you can use the following approach:
Here's a sample code snippet in Java that implements this approach:
In this example, we have an array of numbers from 1 to 6, with one number missing (3). We call the findMissing() method, passing in the array and the value of n (which is the length of the array plus one).
The findMissing() method calculates the sum of all the numbers from 1 to n using the formula sum = n * (n + 1) / 2, then calculates the sum of the array using a loop. The missing number is then calculated by subtracting the sum of the array from the sum of all the numbers from 1 to n.
Krishnapriya Rajeev
24-Mar-2023The code given below shows how to find the missing number in a non-duplicating array of numbers:
We can obtain the missing element by subtracting the sum of all elements from the sum of first n natural numbers, where n is the largest number in the array.
Ravi Vishwakarma
22-Nov-2021class HelloWorld {public static void main(String[] args) {
int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println('Missing Number is '+ missingNumber);
}
public static int findMissingNum(int[] array) {
int n=array.length+1;
int sumOfFirstNNums=n*(n+1)/2;
int actualSumOfArr=0;
for (int i = 0; i < array.length; i++) {
actualSumOfArr+=array[i];
}
return sumOfFirstNNums-actualSumOfArr;
}
}
Output.
Missing Number is 1