We can solve this problem in two different ways. Let’s check the first method.
Method 1:
Input Array = [1, 2, 3, 4, 4] => Range is from 1 to 5 but 4 is a duplicate element in this range.
package main import "fmt" func duplicateInArray(arr []int) int{ visited := make(map[int]bool, 0) for i:=0; i<len(arr); i++{ if visited[arr[i]] == true{ return arr[i] } else { visited[arr[i]] = true } } return -1 } func main(){ fmt.Println(duplicateInArray([]int{1, 2, 3, 4, 4})) fmt.Println(duplicateInArray([]int{4, 5, 6, 7, 7})) fmt.Println(duplicateInArray([]int{1, 2, 3, 4, 5})) }
4 7 -1
Now, let’s check the second method to solve this problem.
Method 2: Using XOR operation
Input Array = [1, 2, 3, 4, 4] => Range is from 1 to 5 but 4 is duplicate in that range.
Range is from 1 to 5. => XOR => 0^1^2^3^4^4^0^1^2^3^4 => 4 (since 0^1=1).
package main import "fmt" func duplicateInArray(arr []int, r int) int{ xor := 0 for i:=0; i<len(arr); i++{ xor ^= arr[i] } for j:=1; j<=r-1; j++{ xor ^= j } return xor }
4 3 1 0