Missing Number
Missing Number
Missing Number
AfterAcademy
Admin AfterAcademy
10 Aug 2020
Missing Number
Difficulty: Easy
https://afteracademy.com/blog/missing-number/ 1/10
1/2/25, 12:17 PM Missing Number
Problem Note: Your algorithm should run in linear runtime complexity. Could
you implement it using only constant extra space complexity?
There will be only one missing number in the given array, two missing
numbers will not be there. Also, if there is no missing number then you
have to return the number that is coming just after the largest element of
the array.
Example 1
Example 2
Example 3
https://afteracademy.com/blog/missing-number/ 2/10
1/2/25, 12:17 PM Missing Number
Solutions
We will be discussing three solutions for the problem
1. Sorting: Sort the array and compare each index with the value at that
index, if it's not equal then return the index
2. Hashing: Store the values of the array in a hashmap and iterate over
the range from 0 to n.
3. Sum of n whole numbers: Find the sum of n numbers and the sum of
the array and return the difference between them.
1. Sorting
To find the missing number in the range of size of the array, we can easily
sort the array knowing that the values in the array are in the range of size of
the array and they are not duplicate.
So, If we sort the array, then we can conclude that the first number not
matching with its index value is our missing number.
Solution Steps
iterate over the array until arr[idx] == idx otherwise, return idx
as the answer.
Pseudo Code
return i
}
}
return i+1
}
Complexity Analysis
2. Hashing
We can create a set or hashmap to store each value inside it knowing that
search operation inside a set or hashmap is O(1). Now if we iterate over the
range from 0 to the size of the array, then we can look for each value
whether or not they are present inside the set. The first number not found
in the set will be our answer.
Solution Steps
Return the first element not present inside the set or hashmap.
Pseudo Code
https://afteracademy.com/blog/missing-number/ 4/10
1/2/25, 12:17 PM Missing Number
Complexity Analysis
So, we can deduce that the difference of the sum of N whole numbers and
the sum of the array will be the missing number.
https://afteracademy.com/blog/missing-number/ 5/10
1/2/25, 12:17 PM Missing Number
Consider example 2,
Solution Steps
Pseudo Code
Complexity Analysis
https://afteracademy.com/blog/missing-number/ 6/10
1/2/25, 12:17 PM Missing Number
Enjoy Algorithms!
https://afteracademy.com/blog/missing-number/ 7/10
1/2/25, 12:17 PM Missing Number
https://afteracademy.com/blog/missing-number/ 8/10
1/2/25, 12:17 PM Missing Number
https://afteracademy.com/blog/missing-number/ 9/10
1/2/25, 12:17 PM Missing Number
https://afteracademy.com/blog/missing-number/ 10/10