Given an array of n-1 distinct integers in the range of 1 to n, find the missing number in it in linear time.

For example, consider array {1, 2, 3, 4, 5, 7, 8, 9, 10} whose elements are distinct and within the range of 1 to 10. The missing number is 6.

Practice this problem

1. Using the Formula for Sum of First n Natural Numbers

We know that the sum of the first n natural numbers can be computed using the formula 1 + 2 + … + n = n×(n+1)/2. We can use this formula to find the missing number.

The idea is to find the sum of integers between 1 and n+1 using the above formula where n is the array’s size. Also calculate the actual sum of integers in the array. Now the missing number would be the difference between the two.

This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The missing number is 6

Java


Download  Run Code

Output:

The missing number is 6

Python


Download  Run Code

Output:

The missing number is 6

2. Using XOR operator

We know that XOR of two equal numbers cancels each other. We can take advantage of this fact to find the missing number in the limited range array.

The idea is to compute XOR of all the elements in the array and compute XOR of all the elements from 1 to n+1, where n is the array’s size. Now the missing number would be the XOR between the two.

This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The missing number is 6

Java


Download  Run Code

Output:

The missing number is 6

Python


Download  Run Code

Output:

The missing number is 6

The time complexity of both above-discussed methods is O(n) and doesn’t require any extra space, where n is the size of the input.