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.
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.
Student
An MBA in finance imparts and improves management aptitude, inventive ability, critical thinking ability, and so forth. It offers a real-time experience that fabricates a staunch career foundation for students and working professionals. It helps them to thoroughly understand the financial sector.
o 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.
The 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.
class 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