Golang program to find the union of two arrays


In Golang, like other programming languages, we can find the union of two arrays. The union of two arrays is a list that consists of elements that lie in array A and the elements that lie in array B and common elements that lie in both arrays.

For example, we have two arrays listed below

A = {2, 9, 5, 7, 3}

B = {5, 8, 7 2, 1}

The union of the above arrays will be

Union = {1, 2, 3, 5, 7, 8, 9}

Method 1

In this method, we are going to find the union of two unsorted arrays. For this, we are going to use a set data structure in Golang. The time complexity of this method is O(n + m) where n and m are the size of the arrays.

Algorithm

Step 1: import all the required packages

Step 2: Declare the struct of type void and then create a variable of void type.

Step 3: Define the printArray() function in which we have passed the array with its size and printing array values using the loop.

Step 4: Start the main function.

  • Declaring and initializing two arrays A and B.

  • Create a set in which we are going to insert the elements. Set has a property of storing unique elements only so if there are the same elements within the same array or both arrays it will store that element one time only.

  • Print both the list using the printArray() function.

  • Run a for loop for both arrays separately and append the elements in the set.

  • Lastly, print all the elements of the set.

Example

This is the code to find the union of the unsorted arrays with the help of a set data structure that has the property of storing unique elements.

package main

import "fmt"

// creating a void struct data type
type void struct{}

var member void

// function to print the array with array and
// size of the array as argument
func printArray(array []int, size int) {
   for i := 0; i < size; i++ {
       fmt.Print(array[i], " ")
   }
   fmt.Println()
}

func main() {
   // declaring and initializing the slice
   // listA and listB of type int
   listA := []int{8, 4, 7, 1, 6}
   listB := []int{5, 3, 2, 3, 4, 7}

   //This is the way in Golang to create a set
   // using map where value is void=struct{}
   set := make(map[int]void)

   fmt.Print("List A: ")
   printArray(listA, 5)

   fmt.Print("List B: ")
   printArray(listB, 6)

   // running for loop over listA and adding all
   //The elements in the set
   for i := 0; i < 5; i++ {
       set[listA[i]] = member
   }

   // running for loop over listA and adding all
   //The elements in the set
   for i := 0; i < 6; i++ {
       set[listB[i]] = member
   }

   fmt.Print("The union of the above lists is: ")

   // printing all the keys of the set
   for k, _ := range set {
       fmt.Print(k, " ")
   }
   fmt.Println()
}

Output

List A: 8 4 7 1 6 
List B: 5 3 2 3 4 7 
The union of the above lists is: 3 2 8 4 7 1 6 5 

Method 2

In this method, we are going to find the union of two unsorted arrays for which we will sort them and then apply the logic accordingly. The time complexity for this function will be O((N + M)log(N+M)).

Algorithm

Step 1: import all the required packages.

Step 2: Declare the struct of type void and then create a variable of void type.

Step 3: Define the printArray() function in which we have passed the array with its size and printing array values using the loop.

Step 4: Start the main function.

  • Declaring and initializing two arrays A and B.

  • Sort both arrays using the sort.Ints() function.

  • Call the unionOfSortedArrays() function by passing arrays and their size as arguments.

Step 5: Start of unionOfSortedArrays() function.

  • Declaring and initializing an array with the name unionArray that will hold the union of both arrays.

  • Run a for loop over both arrays and compare elements of one array with other elements and add in unionArray if that element is not added already.

  • Run individual loop over both arrays separately and add those elements in unionArray.

Example

This is the code to find the union of the unsorted arrays by first sorting them and then running a loop over both arrays.

package main

import (
    "fmt"
    "sort"
)

// function to print the array with array and
// size of the array as argument
func printArray(array []int, size int) {
    for i := 0; i < size; i++ {
        fmt.Print(array[i], " ")
    }
    fmt.Println()
}

// unionOfSortedArray is a function with an array and
// integer as the argument and array, an integer as return type
func unionOfSortedArray(listA []int, sizeA int, listB []int, sizeB int) ([]int, int) {
    // declaring iterator variables and unionArray to store union values
    var unionArray []int
    var i, j int

    // declaring and initializing iterators
    i = 0
    j = 0

    // running for loop over both the arrays
    for i < sizeA && j < sizeB {
        // if element at index i in listA is less than equal to listB
        // then we are appending in unionArray if the last element is not
        // same
        if listA[i] <= listB[j] {
            if len(unionArray) == 0 || unionArray[len(unionArray)-1] != listA[i] {
                unionArray = append(unionArray, listA[i])
            }
            i++
        } else {
            if len(unionArray) == 0 || unionArray[len(unionArray)-1] != listB[j] {
                unionArray = append(unionArray, listB[j])
            }
            j++
        }
    }

    // iterating over listA if any element is uniterated
    for i < sizeA {
        if unionArray[len(unionArray)-1] != listA[i] {
            unionArray = append(unionArray, listA[i])
        }
        i++
    }

    // iterating over listB if any element is uniterated
    for j < sizeB {
        if unionArray[len(unionArray)-1] != listB[j] {
            unionArray = append(unionArray, listB[j])
        }
        j++
    }
    return unionArray, len(unionArray)
}

func main() {
    // declaring and initializing the slice
    // listA and listB of type int
    listA := []int{8, 4, 7, 1, 6}
    listB := []int{5, 3, 2, 3, 4, 7}

    fmt.Println("Golang program to find the union of two sorted arrays.")

    fmt.Print("List A: ")
    printArray(listA, 5)

    fmt.Print("List B: ")
    printArray(listB, 6)

    // sorting both the array in increasing order
    sort.Ints(listA)
    sort.Ints(listB)

    fmt.Println("Arrays after sorting")
    fmt.Print("List A: ")
    printArray(listA, 5)

    fmt.Print("List B: ")
    printArray(listB, 6)
    // calling function by passing both arrays and their size as an argument
    unionArray, size := unionOfSortedArray(listA, 5, listB, 6)

    fmt.Print("The union of the above lists is: ")
    printArray(unionArray, size)
}

Output

Golang program to find the union of two sorted arrays.
List A: 8 4 7 1 6 
List B: 5 3 2 3 4 7 
Arrays after sorting
List A: 1 4 6 7 8 
List B: 2 3 3 4 5 7 
The union of the above lists is: 1 2 3 4 5 6 7 8

Conclusion

In this article, we have explored how to find the union of sorted and unsorted arrays in Golang. In the first method, using the set data structures we are reducing the time complexity but at the same time we are increasing the space complexity. Whereas in the second method, we are using a sorting algorithm that is increasing the time complexity but reduces the space complexity. To learn more about Golang you can explore these tutorials.

Updated on: 10-Jul-2023

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements