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, find it.
51322-Nov-2021
Updated on 28-Apr-2023
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-2021Output.
Missing Number is 1