Task Description
Given an array of integers which contains numbers from [1,n] except two numbers. We need to find those two missing numbers.Example
Sample Input 1:
input_array = [1, 2, 7, 9, 3, 6, 4]
Sample Output 1:
missing numbers = 5, 8
Sample Input 2:
input_array = [2, 7, 9, 3, 6, 4, 5, 8]
Sample Output 2:
missing numbers = 1, 10
Naive Solution, Hashing Solution and Sorting Solution
If the size of input array is $n$, then we are looking for the numbers $[1,\ N]]$ inclusive where $N = n + 2$.Similar to the Single Missing Number Problem, the Naive solution, Hashing solution and Sorting solution can be implemented in the similar fashion with similar Time and Space Complexity. The changes to be made are minor. Can you try it?
Solution 2: Using Sum of Numbers and XOR Together
Sum of numbers method and XOR of numbers method can not be applied alone to compute the two missing numbers. However, we can combine those two methods to get our result.Principle - Part 1 (Compute Pivot)
If $x$ and $y$ be the two missing numbers, then it can be guaranteed that the two numbers will lie on the either side of a $Pivot$ number because we are talking about Unique Numbers from $1$ to $N$, and $x$ and $y$ are also Unique.$x+y$ can be computed by the Sum of Numbers technique we applied in Single Missing Number Problem to compute single missing number. The same method here will give us the sum of two missing numbers. After we have the sum, we can compute $Pivot = sum / 2$
Principle - Part 2 (Compute Missing Numbers)
After we have chosen the $Pivot$ number we can compute the missing number on the either sides by using XOR technique.The missing number in the lower half can be computed by computing XOR of
- all numbers from $1$ to $Pivot$, and
- all numbers $\le Pivot$ in the input array
Similarly, the missing number in the uppoer half can be computed by computing XOR of
- all numbers from $Pivot + 1$ to $N$, and
- all numbers $\gt Pivot$ in the input array
Implementation
Following the implementation of above principle:
No comments:
Post a Comment