C# Program to Find Missing Number in Array
n*(n+1)/2 and subtracting the actual sum of array elements, like int missing = totalSum - actualSum;.Examples
How to Think About It
n*(n+1)/2. Then find the sum of the given array elements. The difference between these two sums is the missing number.Algorithm
Code
using System; class Program { static void Main() { int[] arr = {1, 2, 4, 5, 6}; int n = arr.Length + 1; int totalSum = n * (n + 1) / 2; int actualSum = 0; foreach (int num in arr) { actualSum += num; } int missing = totalSum - actualSum; Console.WriteLine(missing); } }
Dry Run
Let's trace the example array [1, 2, 4, 5, 6] through the code
Calculate n
Array length is 5, so n = 5 + 1 = 6
Calculate total sum
totalSum = 6 * (6 + 1) / 2 = 21
Calculate actual sum
Sum of array elements = 1 + 2 + 4 + 5 + 6 = 18
Find missing number
missing = totalSum - actualSum = 21 - 18 = 3
| Step | Value |
|---|---|
| n | 6 |
| totalSum | 21 |
| actualSum | 18 |
| missing | 3 |
Why This Works
Step 1: Calculate expected sum
Using the formula n*(n+1)/2 gives the sum of all numbers from 1 to n, which is what the array should contain if no number was missing.
Step 2: Sum actual array elements
Adding all elements in the array gives the sum of the numbers present.
Step 3: Subtract to find missing
The difference between the expected sum and actual sum is the missing number because that number was not added in the actual sum.
Alternative Approaches
using System; class Program { static void Main() { int[] arr = {1, 2, 4, 5, 6}; int n = arr.Length + 1; int xorAll = 0; for (int i = 1; i <= n; i++) { xorAll ^= i; } int xorArr = 0; foreach (int num in arr) { xorArr ^= num; } int missing = xorAll ^ xorArr; Console.WriteLine(missing); } }
using System; class Program { static void Main() { int[] arr = {1, 2, 4, 5, 6}; int n = arr.Length + 1; bool[] present = new bool[n + 1]; foreach (int num in arr) { present[num] = true; } int missing = 0; for (int i = 1; i <= n; i++) { if (!present[i]) { missing = i; break; } } Console.WriteLine(missing); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through the array once to sum elements, so it runs in linear time relative to the array size.
Space Complexity
Only a few variables are used for sums and counters, so the space used is constant.
Which Approach is Fastest?
The sum formula method and XOR method both run in O(n) time and O(1) space, but XOR avoids overflow risk.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sum formula | O(n) | O(1) | Simple and fast for small to medium arrays |
| XOR operation | O(n) | O(1) | Avoids overflow, good for large numbers |
| Boolean array | O(n) | O(n) | When numbers are unsorted or duplicates exist |