Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements