1. Introduction
One of the common problems in array manipulation is to find a missing number in a sequence. Given an array containing n distinct numbers taken from the range 0, 1, 2, …, n, find the one that is missing from the array. The challenge is to solve it without using any extra space, meaning we should not use any other data structures to store elements from the array.
2. Program Steps
1. Calculate the sum of the first n natural numbers using the formula: n*(n+1)/2. This will give us the expected sum if no numbers were missing.
2. Calculate the actual sum of the numbers present in the array.
3. Subtract the actual sum from the expected sum to get the missing number.
3. Code Program
public class MissingNumber {
public static int findMissingNumber(int[] arr) {
int n = arr.length;
// Step 1: Calculate the sum of first n natural numbers
int total = (n * (n + 1)) / 2;
// Step 2: Calculate the actual sum of the numbers in the array
for (int i = 0; i < n; i++) {
total -= arr[i];
}
// Step 3: The remaining total is the missing number
return total;
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 4, 5, 6, 7};
System.out.println("The missing number is: " + findMissingNumber(arr));
}
}
Output:
The missing number is: 3
4. Step By Step Explanation
1. The formula n*(n+1)/2 calculates the sum of the first n natural numbers.
2. By iterating over the array, we subtract each element from the calculated sum. This is because we are trying to find out which number from the expected sequence is not present in our array.
3. After the loop, the remaining value in total is our missing number. This approach uses a constant amount of space, regardless of the size of the input array.