Brainteasers & Puzzles

Two Missing Integers

You hold 98 of the integers from 1 to 100. Two are missing. What totals can you keep as you read the numbers once to pin down exactly which two?

solvedmedium1 min

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 aa and bb. The full set 1 to 100 has known totals

k=1100k=5050,k=1100k2=338350.(1)\sum_{k=1}^{100} k = 5050, \qquad \sum_{k=1}^{100} k^2 = 338350. \tag{1}

Add up the 98 numbers you hold and their squares in a single pass, then subtract,

a+b=5050x,a2+b2=338350x2.(2)a + b = 5050 - \sum x, \qquad a^2 + b^2 = 338350 - \sum x^2. \tag{2}
1255075100??ab
The full set 1 to 100 has a known sum of 5050 and a known sum of squares of 338350. Subtracting the totals of the 98 numbers you hold gives the sum and the sum of squares of the missing pair, and that pair of equations has a single positive solution.

#Solve the pair

Write p=a+bp = a + b and q=a2+b2q = a^2 + b^2. Their difference is recovered through

(ab)2=2qp2    ab=2qp2,(3)(a - b)^2 = 2q - p^2 \;\Longrightarrow\; a - b = \sqrt{2q - p^2}, \tag{3}

and then a=12(p+2qp2)a = \tfrac{1}{2}(p + \sqrt{2q - p^2}) and b=12(p2qp2)b = \tfrac{1}{2}(p - \sqrt{2q - p^2}). 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

v=(12100)(x1x98)=ab.(4)v = \big(1 \oplus 2 \oplus \cdots \oplus 100\big) \oplus \big(x_1 \oplus \cdots \oplus x_{98}\big) = a \oplus b. \tag{4}

Since aba \ne b, the value vv 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 aa and bb directly.