Finding a missing number in an array is a common coding problem that helps improve your understanding of arrays, loops, and basic math. In this article, we’ll walk through three different methods to solve this problem step-by-step using simple language.
You are given an array that contains numbers from 1 to n, but one number is missing. Your task is to find that missing number. For example, if the array is {1, 2, 4, 5}, the missing number is 3.
Method 1. Using Sum Formula.
In this method, we use a simple math formula to find the missing number.
Steps
- Find the total sum of numbers: The sum of the first n natural numbers is calculated using this formula: Sum=n×(n+1)2\text{Sum} = \frac{n \times (n+1)}{2}Sum=2n×(n+1)
- Find the sum of the array: Add up all the numbers in the array.
- Subtract the two sums: The difference between the total sum and the sum of the array gives the missing number.
Code Example
public class MissingNumber {
public static int findMissingNumber(int[] arr, int n) {
// Step 1: Calculate the total sum using the formula
int totalSum = (n * (n + 1)) / 2;
// Step 2: Calculate the sum of array elements
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
// Step 3: Subtract the actual sum from the total sum to get the missing number
return totalSum - actualSum;
}
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5}; // Missing number is 3
int n = 5;
System.out.println("Missing number: " + findMissingNumber(arr, n));
}
}
How Does It Work?
- The formula finds the sum of numbers from 1 to n.
- We subtract the actual sum of the array from the total sum, which gives us the missing number.
Output

Method 2. Using XOR Operation.
This method uses a bitwise operation called XOR. XOR compares two numbers bit by bit. If two numbers are the same, XOR gives 0; if they are different, it gives 1. We can use this property to find the missing number.
Steps
- XOR all the numbers in the array.
- XOR all the numbers from 1 to n.
- XOR the two results: The numbers that appear twice will cancel each other, leaving only the missing number.



Join the conversation! Your thoughts help the community grow.