How to find duplicate elements in an array with Go

2 Answers

0 votes
package main

import "fmt"

func findDuplicates(arr []int) []int {
	appearance := make(map[int]bool)
	duplicates := []int{}

	for _, num := range arr {
		if appearance[num] {
			duplicates = append(duplicates, num)
		} else {
			appearance[num] = true
		}
	}

	return duplicates
}

func main() {
	arr := []int{1, 2, 3, 2, 2, 4, 4, 4, 4, 3, 5, 6, 3}

	fmt.Println(findDuplicates(arr))
}


/*
run:

[2 2 4 4 4 3 3]

*/

 



answered Oct 25, 2024 by avibootz
edited Oct 25, 2024 by avibootz
0 votes
package main

import (
	"fmt"
	"slices"
)

func findDuplicates(arr []int) []int {
	appearance := make(map[int]bool)
	duplicates := []int{}

	for _, num := range arr {
		if appearance[num] && !slices.Contains(duplicates, num) {
			duplicates = append(duplicates, num)
		} else {
			appearance[num] = true
		}
	}

	return duplicates
}

func main() {
	arr := []int{1, 2, 3, 2, 2, 4, 4, 4, 4, 3, 5, 6, 3}

	fmt.Println(findDuplicates(arr))
}


/*
run:

[2 4 3]

*/

 



answered Oct 25, 2024 by avibootz
...