Missing in Array — GeeksforGeeks POTD
1 min readSep 4, 2024
Given an array arr of size n−1 that contains distinct integers in the range of 1 to n (inclusive), find the missing element. The array is a permutation of size n with one element missing. Return the missing element.
Get Subhankar’s stories in your inbox
Join Medium for free to get updates from this writer.
Examples:
Input: n = 5, arr[] = [1,2,3,5]
Output: 4
Explanation : All the numbers from 1 to 5 are present except 4.Input: n = 2, arr[] = [1]
Output: 2
Explanation : All the numbers from 1 to 2 are present except 2.Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ n ≤ 105
1 ≤ arr[i] ≤ n
// User function Template for Java
class Solution {
// Note that the size of the array is n-1
int missingNumber(int n, int arr[]) {
// Calculate the expected sum of numbers from 1 to n
int expectedSum = n * (n + 1) / 2;
// Calculate the sum of the elements in the array
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
// The missing number is the difference between expected sum and actual sum
return expectedSum - actualSum;
}
}





