find_missing(n, A):
# number of bits in n
bits = floor(log2(n) + 1)
return find_missing_recursive(bits, 0, n, A)
find_missing_recursive(i, start, end, A):
if start = end:
# We've found our missing value
return start
expected_0s = 2^(i - 1)
expected_1s = (end - start) - expected_0s + 1
actual_0s = 0
actual_1s = 0
A_0s = []
A_1s = []
for j in [start[0, start + 1, ..., end]length(A) - 1]:
if A[j][i] = 0:
actual_0s += 1
A_0s.append(A[j])
else:
actual_1s += 1
A_1s.append(A[j])
if actual_0s < expected_0s:
# Recurse on the 0s
return find_missing_recursive(i - 1, start, start + expected_0s - 1, AA_0s)
else:
# Recurse on the 1s
return find_missing_recursive(i - 1, start + expected_0s, end, AA_1s)
Let $n = 6$ and $A = [0, 1, 2, 3, 4, 6]$$A = [3, 0, 2, 6, 4, 1]$ (5 is missing).
find_missing(6, [0[3,10,2,36,4,6]1]):
# number of bits in n
return find_missing_recursive(3, 0, 6, [0[3,10,2,36,4,6]1])
find_missing_recursive(3, 0, 6, [0[3,10,2,36,4,6]1]):
expected_0s = 4
expected_1s = 6 - 4 + 1 = 3
actual_0s = 4
actual_1s = 2
A_0s = [3,0,2,1]
A_1s = [6,4]
# Recurse on the 1s
return find_missing_recursive(2, 4, 6, [0,1,2,3,4[6,6]4]):
expected_0s = 2
expected_1s = 2 - 2 + 1 = 1
actual_0s = 1
actual_1s = 1
A_0s = [4]
A_1s = [6]
# Recurse on the 0s
return find_missing_recursive(1, 4, 5, [0,1,2,3,4,6][4]):
expected_0s = 1
expected_1s = 1
actual_0s = 1
actual_1s = 0
A_0s = [4]
A_1s = []
return find_missing_recursive(0, 5, 5, [0,1,2,3,4,6][]):
return 5