You are given 98 distinct integers, each in the range 1 to 100, so exactly two values in that range are missing. What is a good way to find the two missing integers, reading the data only once and using little extra memory?
Reveal solutionHide solution
#Two equations from two totals
Call the missing values and . The full set 1 to 100 has known totals
Add up the 98 numbers you hold and their squares in a single pass, then subtract,
#Solve the pair
Write and . Their difference is recovered through
and then and . One pass, two running totals, constant extra memory.
#The overflow-free variant
If the squares feel large, exclusive-or carries the same information with no growth. Let
Since , the value has at least one bit set. Pick any such bit and split all of 1 to 100 together with the data into the group where that bit is 1 and the group where it is 0. Each group contains exactly one missing number, so the running xor of each group hands you and directly.