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: https://play.golang.org/p/AT1EllmUhMI

package main

import (
	"fmt"
)

//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

fmt.Println(firstDuplicate(c))

fmt.Println(firstDuplicate(d))	
}

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

https://play.golang.org/p/KwLrC4dM-WG

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.)

3 Likes

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.