How to Remove Duplicates in an Array in Golang


The challenge

Remove the left-most duplicates from a list of integers and return the result.

// Remove the 3's at indices 0 and 3
// followed by removing a 4 at index 1
solve([3, 4, 4, 3, 6, 3]); // => [4, 6, 3]

The solution in Golang

Option 1:

package solution 

func Solve(arr []int) (res []int) {
    visited := map[int]bool{}
    for i := len(arr) - 1; i >= 0; i-- {
        n := arr[i]
        if visited[n] { continue }
      
        visited[n] = true
        res = append([]int{n}, res...)
    }
  
    return
}

Option 2:

package solution 

func Solve(arr []int) []int {
  counts := make(map[int]bool)
  for _,x := range arr {
    counts[x]=true
  }
  result := make([]int,len(counts))
  j := len(result)-1
  for i := len(arr)-1; i>=0; i-- {
    if counts[arr[i]] {
      counts[arr[i]] = false;
      result[j] = arr[i]
      j--
    }
  }
  return result
}

Option 3:

package solution 

func Solve(a []int) (r[]int) {
  m:=map[int]int{}
  for _,v:=range a{ m[v]++ }
  for _,v:=range a{
    if m[v]==1{
      r=append(r,v)
    }
    m[v]--
  }
  return
}

Test cases to validate our solution

package our_test

import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
  . "codewarrior/kata"
)

func dotest(arr , exp []int) {
    var ans = Solve(arr)
    Expect(ans).To(Equal(exp))
}

var _ = Describe("Example tests", func() {
  It("It should work for basic tests", func() {       
        dotest([] int{3,4,4,3,6,3}, []int{4,6,3})
        dotest([] int{1,2,1,2,1,2,3}, []int{1,2,3})    
        dotest([] int{1,2,3,4}, []int{1,2,3,4})
        dotest([] int{1,1,4,5,1,2,1}, []int{4,5,2,1})
        dotest([] int{1,2,1,2,1,1,3}, []int{2,1,3})
        dotest([] int{0,4,4,3,0,3}, []int{4,0,3})       
  })
})