Can I get around nested loops?

Hi, I’m extremely new to Go and am wondering if I could get a pointer here. I was working on solving a problem on codefights, I solved the problem to the extent of getting correct answers, I can’t figure out how to make it execute under 4 seconds. I’m guessing there is a better way than nesting loops?

Link to Go Playground and shown code below. If anything stands out that should be done differently I’d love to know that as well.

Go Playground:

package main

import (

//find the number that is duplicated first in the array

func firstDuplicate(a []int) int {
    s := []int{}
	for _, fVal := range a {
		for _, val := range s {
			if val == fVal {
				return val
		s = append(s, fVal)
	return -1

func main() {
c := []int{2, 3, 3, 1, 5, 2} //returns 3
d := []int{1, 1, 2, 2, 1}  //returns 1



You can use a map, which gives you constant time lookups on the previously seen values.

I’m sure there are more efficient structures we could use, given that we know it’s just ints we have to track. But this one is easy and built in to the language.

(The struct{} oddness is a zero size type, since all we need is map that tracks whether a value exists, not what that value is.)


Wow! Thanks for the fast and great response! I appreciate the explanation of the struct part as well, I don’t think I’ve ever see it used like that.