Missing Number
Problem
An array has n different numbers taken from 0, 1, 2, ..., n. So exactly one number of this range is missing. Print the missing number.
Constraints
- 1 <= n <= 10^5
Examples
Input
3 3 0 1
Output
2
Solutions
We know the sum of 0..n. The array sum is smaller by exactly the missing number.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The missing number.
* Approach: Compare with the expected sum.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: The numbers 0..n have the sum n * (n + 1) / 2.
long n = a.length;
long expected = n * (n + 1) / 2;
// Step 2: Add all numbers that are in the array.
long actual = 0;
for (int value : a) {
actual += value;
}
// Step 3: The difference is the missing number.
return expected - actual;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- What is the sum of 0 to n?