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.
To find the missing number in an array of non-duplicating numbers from 1 to n, you can use the mathematical formula for the sum of the first n natural numbers. The sum of the first n natural numbers is given by the formula:
[ \text{Sum} = \frac{n \times (n + 1)}{2} ]
You can calculate the expected sum using this formula and then subtract the sum of the elements in the array from it. The difference will give you the missing number.
Here's an efficient Java program to implement this approach:
public class MissingNumberFinder {
public static int findMissingNumber(int[] nums) {
int n = nums.length + 1; // Since one number is missing
int expectedSum = n * (n + 1) / 2; // Sum of first n natural numbers
int actualSum = 0;
// Calculate the sum of the elements in the array
for (int num : nums) {
actualSum += num;
}
// The missing number is the difference between expected and actual sum
return expectedSum - actualSum;
}
public static void main(String[] args) {
int[] nums = {1, 2, 4, 5, 6}; // Example array with missing number 3
int missingNumber = findMissingNumber(nums);
System.out.println("The missing number is: " + missingNumber);
}
}
nums
which contains numbers from 1 to n with one number missing.