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

Go ProgrammingServer Side ProgrammingProgramming

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
raja
Published on 04-Feb-2021 15:52:29
Advertisements