You are given an array of positive numbers from 11 to nn, such that all numbers from 11 to nn are present except one number, xx. You have to find xx. The input array is not sorted.
For example, let’s look at the array below.
Linear, O(n)O(n).
Constant, O(1)O(1).
A naive solution is to simply search for every integer between 1 and n in the input array, stopping the search as soon as there is a missing number. Since the input array is not sorted, its time complexity will be O(n2O(n2).
Can you do better than O(n2O(n2)? Yes.
You could sort the array and then do a linear scan O(nO(n) where you compare all consecutive elements to find the missing number. However, the time complexity of this algorithm is O(nlognO(nlogn) due to the time spent in sorting.
You can do better. Here is a linear, O(nO(n), solution that uses the arithmetic series sum formula.
∑1n=n(n+1)21∑n=2n(n+1)
Here are the steps to find the missing number.
Find the sum of elements of all the numbers in the array.
Let’s call it sum. This would require a linear scan, O(n).
Then find the expected sum of the first n numbers using the formula: 2(n(n+1)). Let’s call it total.
The difference between total and sum is the missing number in the array.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!