Find Missing and Repeating Number
An array holds numbers 1..n but one number is missing and another appears twice. Find both in O(n) time, O(1) space.
Intuition
Two unknowns need two equations. The sum of the array differs from the expected 1..n sum by (repeat − missing), and the sum of squares differs by (repeat² − missing²). Divide the two and you get repeat + missing — now it's two linear equations.
Approach
Set up the two equations
Let R = repeating, M = missing. S − S_n = R − M and S² − S²_n = R² − M², where S, S² are the actual sums and S_n, S²_n the expected ones.
Factor the squares
R² − M² = (R − M)(R + M), so dividing the second difference by the first gives R + M directly.
Solve
R = ((R−M) + (R+M)) / 2 and M = R − (R − M). Two O(n) passes worth of arithmetic, constant extra space.
Solution & live demo
Edge cases
Pure algebra — positions don't matter.
Sum of squares reaches ~n³/3; use 64-bit. Python unaffected.