twoMissingNumbers.md
July 31, 2024 ยท View on GitHub
Description:
Given an unsorted set of numbers from 1 to N with exactly two of them missing, find those two missing numbers.
Examples
Example 1:
Input: prices = [3, 2, 5, 1, 6, 8] Output: [4,7]
Example 2:
Input: prices = [3, 2, 5, 1, 6, 4] Output: [7,8]
Algorithmic Steps This problem is solved with the help of sequential numbers sum and average calculations. The algorithmic approach can be summarized as follows:
-
Initialize missing two numbers array(i.e,
missingTwoNums) to an empty array. -
Store the length of input array along with missing numbers into
lenvariable(i.e,len = nums.length+2). -
Calculate the sum of all sequential numbers into
sumvariable.Note: Sum of
nsequential number sum is(n *(n+1))/2. -
Calculate the sum of given input array into
numsSumby iterating over the array. -
The sum of missing two numbers(
missingTwoNumsSum) is calculated by the difference between sum calculated in step 3 & 4. -
Find the average of missing two numbers sum into
missingTwoNumsAvg. -
Calculate the sequential numbers sum until missing numbers average value and store it in
sumUntilAvg. -
Also, calculate the sum of numbers until
missingTwoNumsAvgintonumsSumUntilAvgby iterating over the input array. -
The difference between sums in step7 & 8 gives the first missing number. This number can be pushed to
missingTwoNumsarray. -
The second number is calculated by deducting first number from missing numbers sum. This number also stored into
missingTwoNumsarray. -
Return
missingTwoNumsarray which stores two missing numbers.
Time and Space complexity:
This algorithm has a time complexity of O(n)(O(n) + O(n)), where n is the number of stock prices. This is because we are traversing the array two times.
Here, we don't use any additional datastructure other than missing numbers array of size 2. Hence, the space complexity will be O(1).