Problem Name: Missing Number in an Array
Dhruva Bhat S N
Passionate Web Developer | Crafting Innovative Solutions with Expertise in Frontend & Backend Technologies | Intern @ Cloud Ambassadors
This Problem is on GFG Sheet
Problem Link
Problem Statement :
Given an array of size n-1 such that it only contains distinct integers in the range of 1 to n. Return the missing element.
Example 1
Input: n = 5, arr[] = {1,2,3,5}
Output: 4
Explanation : All the numbers from 1 to 5 are present except 4.
Example 2
Input: n = 2, arr[] = {1}
领英推荐
Output: 2
Explanation : All the numbers from 1 to 2 are present except 2.
Approach
The function missingNumber takes an array of integers array and the size of the intended sequence n as input. It returns the missing number in the sequence of consecutive integers from 1 to n.
The code works by first calculating the expected sum of all consecutive integers from 1 to n. This is done using the formula (n * (n + 1)) // 2.
Next, the code iterates through the given array and accumulates the sum of the elements.
Finally, the code subtracts the actual sum from the expected sum to find the missing number. This is because the difference between the expected sum and the actual sum represents the sum of the missing elements in the sequence.
Java Code
class Solution {
int missingNumber(int array[], int n) {
// Your Code Here
int tot=(n*(n+1))/2;
int sum=0;
for(int i=0;i<n-1;i++){
sum+=array[i];
}
int res=tot-sum;
return res;
}
}