Re: searching for missing element in an array



srk wrote:
Hi,
Suppose we have n numbers(from 1 to n) and there is an array of size
n-1. How can we find, which number is missing from the array if
numbers 1 to n are being placed in array randomly.

There are other ways to do it but,
your question is an xor checksum exercise.

xor all the numbers from 1 to n,
and xor that result with the xor of all the numbers in the array.
The result will be the missing value.

Suppose n is 4
and there's only 3 elements in the array

1 xor 2 xor 3 xor 4 is (4).

Take that result, (4),
and xor (4) with the xor of all the elements in the array.
The result will be the missing value.

If the array is {4,2,3}, the missing value is 1.
(4 xor 2 xor 3) xor (4) is 1

If the array is {4,3,1}, the missing value is 2.
(4 xor 3 xor 1) xor (4) is 2

If the array is {2,1,4}, the missing value is 3.
(2 xor 1 xor 4) xor (4) is 3

If the array is {3,2,1}, the missing value is 4.
(3 xor 2 xor 1) xor (4) is 4


--
pete
.



Relevant Pages

  • Re: searching for missing element in an array
    ... What happens if the array was initialized to all -1 values? ... we know that a zero is stored in the slot of the missing number? ... initialization of the array. ... that there are n-1 numbers present. ...
    (comp.programming)
  • Re: searching for missing element in an array
    ... What happens if the array was initialized to all -1 values? ... we know that a zero is stored in the slot of the missing number? ... initialization of the array. ... there are n-1 numbers present. ...
    (comp.programming)
  • Re: searching for missing element in an array
    ... What happens if the array was initialized to all -1 values? ... we know that a zero is stored in the slot of the missing number? ... The original problem statement makes not statement about the ... there are n-1 numbers present. ...
    (comp.programming)
  • Re: question about max_readahead for ide devices in 2.4?
    ... Andrew> That's correct - it's all a bit weird. ... sets an entry in the read_aheadarray. ... Or am I missing something else?? ... send the line "unsubscribe linux-kernel" in ...
    (Linux-Kernel)
  • Re: array Puzzle (spoiler)
    ... >) The key is that the integers in the input array are sequential, ... > So now you know one value, and the sum of the two others. ... some of the missing values is generally applicable. ... None of these ranges can contain *all* of the missing values, ...
    (comp.programming)