[Python] Union of Two Arrays


Find the set of all elements in two arrays, i.e., union of two arrays in Python.

The idea is to convert one array to the data structure of key-value pairs, i.e., hash table. The hash table in Python is built-in dictionary type. Then we check if items of the other array is in the hash table. If not, append the item to the first array, and return the first array after finish.

The following is the implementation of above idea.

Run Code on repl.it

def union(a, b):
      map = {}

      for x in a:
              map[x] = True

      for x in b:
              if x not in map:
                      a.append(x)

      return a


if __name__ == "__main__":
      a = [1, 2, 3, 4, 5]
      b = [2, 3, 5, 7, 11]
      print(union(a, b))

The result will be [1, 2, 3, 4, 5, 7, 11].

The same idea can be used to find intersection of two arrays. See [1]

Tested on:


References:

[1][Python] Intersection of Two Arrays