[Golang] Set Difference of Two Arrays


Find the elements in one array but not in the other, i.e., set difference of two arrays. In mathematical term:

A − B = {x ∈ A and xB}

The idea is to convert the array B to the data structure of key-value pairs, i.e., hash table. The hash table in Go is built-in map type. Then we check if items in array A is in the hash table. If not, append the item to the difference array, and return the difference array after finish.

The following is the implementation of above idea.

Run Code on Go Playground

package main

import (
      "fmt"
)

// Set Difference: A - B
func Difference(a, b []int) (diff []int) {
      m := make(map[int]bool)

      for _, item := range b {
              m[item] = true
      }

      for _, item := range a {
              if _, ok := m[item]; !ok {
                      diff = append(diff, item)
              }
      }
      return
}

func main() {
      var a = []int{1, 2, 3, 4, 5}
      var b = []int{2, 3, 5, 7, 11}
      fmt.Println(Difference(a, b))
}

The result will be [1 4].

Tested on: Go Playground


References:

[1][Golang] Intersection of Two Arrays
[2][Golang] Union of Two Arrays