[Golang] Intersection of Two Arrays


Find common elements in two arrays, i.e., intersection or matches in two arrays. There are many ways to find the intersection [1] [3]. Here we will implement the method mentioned in [2].

The idea is to convert one array 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 of the other array is in the hash table. If yes, the item is in the intersection of the two arrays.

The following is example of above idea.

Run Code on Go Playground

package main

import (
      "fmt"
)

func Intersection(a, b []int) (c []int) {
      m := make(map[int]bool)

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

      for _, item := range b {
              if _, ok := m[item]; ok {
                      c = append(c, item)
              }
      }
      return
}

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

The result will be [2 3 5].

For union of two arrays, see [5].

Tested on: Go Playground


References:

[1]
[2]efficiency - Quick algorithm to find matches between two arrays - Software Engineering Stack Exchange
[3]
[4]
[5][Golang] Union of Two Arrays