Given an array
Output: [5,6]
Explanation: Missing numbers from array are 5, 6 as array should have numbers from 1-8.
Output: [2]
Explanation: Missing numbers from array 2 as array should have numbers from 1-2.
Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Contents
Solution 1 - Store numbers in a HashSet, then loop through from 1-n to find missing Solution 2 - Mark visited indexed numbers first, then find missing numbers (Answer to follow-up question)
In this approach, we are going going to store input array
Complexity Analysis:
Time complexity: O(n) where
Space complexity: O(n) since we are using
As per the problem statement, the numbers will be in range
We first go through elements of the input array
Now, we know that each number will have an associated index in the array, so will be markig those indexes as visited by making number at that index negative. But some numbers may be repeated, for example say if the input array is [2, 2, 2, 4]
-
When we are at index
0 , number in the array is2 so the corresponding index will be2-1= 1 , so mark the number at index 1 to negative, so it becomes [2, -2, 2, 4]. -
When we are at index
1 , number in the array is already negative-2 so in this case we have to take absolute value to get the corresponding indexabs(-2) -1 = 1 , so mark the number at index 1 to negative, but the number is already negative, so when marking a number as negative, either ignore marking it again (or) take-1 * abs(nums[i]) so it becomes [2, -2, 2, 4].
. - By the time we loop through all elements and mark the numbers, it is gonna look like this [2, -2, 2, -4].
.
.
Now, we will loop through array after marking, and if the number is still positive, that means it is a missing number which is equal to
Complexity Analysis:
Time complexity: O(n) where
Space complexity: O(1), since we are modifying input array itself and not using any intermediate data structure to store data.
Above implementations source code can be found at