Write a Golang program to find duplicate elements in a given array


Examples

  • Input Array = [1, 3, 5, 6, 1] => Duplicate element is 1;
  • Input Array = [1, 3, 5, 6, 7] => return -1

Approach to solve this problem

  • Step 1: Define a method that accepts an array.
  • Step 2: Declare a visited map.
  • Step 3: Iterate the given array. If the element exists in the visited map, then return that element.
  • Step 4: Else, return -1.

Program

Live Demo

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, 4, 7, 2, 2}))
   fmt.Println(duplicateInArray([]int{1, 4, 7, 2, 3}))
}

Output

2
-1

Updated on: 04-Feb-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements