1

The following code work well and finds the missing number of contiguous array using XOR. I would like to ask why the first loop starts at 1 and ends at n and the second starts at 2 and ends at n+2?

a = [1, 2, 3,4, 5, 6,8] 
n = len(a)
x1 = a[0]
x2 = 1
for i in range(1, n):
 ##   print (i)
#print (' ')
for i in range(1, n): 
        x1 = x1 ^ a[i]
        print (a[i],x1)
print (' ')
for i in range(2, n + 2): 
        x2 = x2 ^ i 
    ##    print (i,x2)
##print (' ')
print (x1 ^ x2 )
4
  • Because you do so Commented Jul 14, 2019 at 12:06
  • because for i in range(1, n) and for i in range(2, n + 2)... Commented Jul 14, 2019 at 12:07
  • What is the real question? Commented Jul 14, 2019 at 12:08
  • Why shouldn't it work with 0..n and 0..n+1? Commented Jul 14, 2019 at 12:08

1 Answer 1

2

the fact that the ranges don't start at 0 is due to the fact you initialize x1 and x2 to the first value of the array.

you can start at 0 just as easily, with x1, x2 = 0, like this:

a = [1, 2, 3, 4, 5, 6, 8]
n = len(a)
x1 = 0
x2 = 0
for i in range(0, n):
    x1 = x1 ^ a[i]
for i in range(0, n + 2):
    x2 = x2 ^ i
print(x1 ^ x2) # still prints 7

the fact you go all the way to n+2 (which is actually just up to n+1 because the end is not inclusive) is because the array has a missing element, so in your case n+1 is 8, and without XORing it to x2 you'd end up with the wrong value (in this case, 15, which is 7^8).

to clarify: you have to XOR the actual values, with the expected values, to find the missing one.

the first range goes on all actual values, while the second one goes on all possible values, which is up to n+1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.