- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Write a Golang program to find duplicate elements in a given range
- Write a Golang program to calculate the sum of elements in a given array
- Golang Program to find the odd-occurring elements in a given array
- Golang Program To Remove Duplicate Elements From An Array
- Write a Golang program to find pairs with given sum in an array(O(nlogn))
- Write a Golang program to find prime numbers in a given range
- Write a Golang program to find pairs with the given sum in an array(O(n2))
- Write a Golang program to find pairs with the given sum in an array(O(n))
- Golang Program To Find Common Array Elements
- Write a Golang program to reverse an array
- Write a Golang program to find the factorial of a given number (Using Recursion)
- Write a Golang program to find the sum of digits for a given number
- C# program to find all duplicate elements in an integer array
- Write a Golang program to find the frequency of an element in an array
- Write a Golang program to find the frequency of each element in an array

Advertisements