# Repeated number in array

Tags: , , ,

In last post : Find missing number in array, we learned how to find a missing number in array of integers with values in a given range. Today, we will learn how find a repeated number in array of integers from 1 to N. Note that here also, numbers are not sorted but are confined to a range. So, if size of array is N, then range of numbers is from 1 to N-1 as one number is repeated. For example:

```A = [1,2,3,3,4,5]. Repeated number is 3
Size of array : 6 Range : 1 to 5
```

## Algorithm

As we have learned while solving the missing number problem earlier, the XOR principle can be applied here too. Why? Because in this case repeated numbers will be XORed with itself three times. Properties of XOR to understand the method and how we use them.

```A XOR A = 0
0 XOR A = A
```

Now, when a number XORed with itself, the result is zero, and when zero is XORed with a number, the result is the number itself. Extending this, if we XORed the same number thrice or without losing generality, an odd number of times, the result will be the number itself.

Using an odd number of times XOR principle, algorithm to find repeating a number in an array.

1. XOR all actual numbers in the array. Call it aXOR.
2. XOR all numbers in range 1 to N-1. Call it eXOR
3. XOR aXOR with eXOR. Result will be repeated number.

This is because all numbers except the repeated number will be XORed even number of times, and cancel each other. The repeated number will be XORed thrice, the final result will be the repeated number. Let’s take the above example and see if it works

```A = [1,2,2,3,4]

aXOR = 001 XOR 010 = 011 XOR 010 = 001 XOR 011 = 010 XOR 100 = 110
eXOR = 001 XOR 010 = 011 XOR 011 = 000 XOR 100 = 100

ActualXOR XOR expectedXOR = 110 XOR 100 = 010
```

### Implementation

```public int repeatedNumber(int[] nums) {

int n =  nums.length;

int nXOR = 0;
for(int i=0; i<=n; i++){
nXOR ^= i;
}

int aXOR = 0;
for(int i=0; i<n; i++){
aXOR ^= nums[i];
}

return aXOR ^ nXOR;
}
```

The time complexity of the XOR method to find a repeated number in an array is O(n).

Please share your thoughts through comments, if you see something is missing or wrong or not explained properly.