This question exist only because of pure curiosity. Not a homework.
Find the fastest way to find two missing number in an array 1..n
So, In a related post: Quickest way to find missing number in an array of numbers I found out that you can do this pretty quickly by summing up and substracting total.
but what about 2 numbers?
So, our options are:
Anything else? Possible to have O(n) solution? I found this in ruby section of one of the websites, but any language is considered (unless there are some specific things for a language)
To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff. Now increment the diff as the difference is increased now. Repeat from step 2 until all the missing numbers are not found.
S=a1+...+an
.T=a1*a1+...+an*an
.S'=1+...+n=n(n+1)/2
T'=1^2+...+n^2=n(n+1)(2n+1)/6
.x+y=S'-S
, x^2+y^2=T'-T
.x^2+y^2=(x+y)^2-2xy
=> xy=((S'-S)^2-(T'-T))/2
. And now the numbers are merely the roots of the quadratic in z
: z^2-(S'-S)z+((S'-S)^2-(T'-T))/2=0
.The simple way (and pretty fast too:)
a = [1,2,3,5,7]
b = (1..7).to_a
p b-a #=> [4, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With