Given a limited range array of size n and containing elements between 1 and n+1 with one element missing, find the missing number without using any extra space.

For example,

Input:  { 3, 2, 4, 6, 1 }
Output: The missing element is 5
 
Input:  { 3, 2, 4, 5, 6 }
Output: The missing element is 1
 
Input:  { 3, 2, 4, 5, 1 }
Output: The missing element is 6

Practice this problem

The idea is to calculate the sum of all array elements. Then the missing number is the sum of elements between 1 and n+1 minus the actual sum, i.e., the missing number is:

(1 + 2 … + n + (n+1)) - (arr[0] + arr[1] + … + arr[n-1])

We can find the sum of elements between 1 and n using the following formula:

1 + 2 + … + n = n×(n+1)/2

 
Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The missing element is 5

Java


Download  Run Code

Output:

The missing element is 5

Python


Download  Run Code

Output:

The missing element is 5

We can also solve this problem by taking XOR of all array elements with numbers 1 to n+1. Since the same elements will cancel each other as a^a = 0, 0^0 = 0 and a^0 = a, we will be left with the missing number. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The missing element is 5

Java


Download  Run Code

Output:

The missing element is 5

Python


Download  Run Code

Output:

The missing element is 5

Since the array contains all distinct elements and all elements lie in range 1 to n+1, use this property to solve this problem. Initially check if the missing number lies in range 1 to n. If a missing number is not found in range 1 to n, then the missing number is n+1.

To check if a missing number lies in range 1 to n or not, mark array elements as negative by using array elements as indexes. For each array element arr[i], get the absolute value of element abs(arr[i]) and make the element at index abs(arr[i])-1 negative. Finally, traverse the array again to find the first index, which has a positive value. If a positive number is found at index i, then the missing number is i+1. If no positive element is found, then the missing number is n+1.

 
The algorithm can be implemented as follows in C, Java, and Python. This solution modifies the original array. We can restore the original array before returning by making negative elements positive.

C


Download  Run Code

Output:

The missing element is 1

Java


Download  Run Code

Output:

The missing element is 1

Python


Download  Run Code

Output:

The missing element is 1

The time complexity of all above-discussed methods is O(n), where n is the size of the input.