Not related directly to your error, but your method of creating the union will fail unless Y is a subset of X. This is because the size of the array you are creating is size of X. Instead of discard if it exist/add if it is not there just discard if it exist.