Find elements which are present in first array and not in second in Python

You are given two arrays, your task is to find elements that are present in the first array and not in the second one.

Input: 

arr1[]={1,6,88,5,9,13}

arr2[]={1,6,78,9,3,2}

Output:

88,5,13

Method-1:

This is the brute force method. In this method, we will run two loops and one by one check for each element of arr1, its presence in arr2.

def elementMiss(arr1, arr2, size1, size2): 

  for i in range(size1): 
    for j in range(size2): 
      if (arr1[i] == arr2[j]): 
        break

    if (j == size2 - 1): 
      print(arr1[i], end = " ") 

 
arr1 = [ 1 , 6 , 88 , 5 , 9 , 13 ] 
arr2 = [ 1 , 6 , 78 , 9 , 3 , 2 ] 
size1 = len(arr1) 
size2 = len(arr2) 
elementMiss(arr1, arr2, size1, size2) 
Output:

88 5 13

Time Complexity: O(n^2)

Method-2:

In this method, we use a hash table to store elements of arr2 and then search for elements of arr1 in that table. If element is not found then we print that element.

def elementMiss(arr1, arr2, size1, size2):
  sett = dict()
  for i in range(size2):
    sett[arr2[i]] = 1
  for j in range(size1):
    if arr1[j] not in sett.keys():
      print(arr1[j], end = " ") 

 
arr1 = [ 1 , 6 , 88 , 5 , 9 , 13 ] 
arr2 = [ 1 , 6 , 78 , 9 , 3 , 2 ] 
size1 = len(arr1) 
size2 = len(arr2) 
elementMiss(arr1, arr2, size1, size2) 
Output:

88 5 13

Time Complexity: O(n)

Space Complexity : O(n)

where n is number of elements in arr1

Leave a Reply

Your email address will not be published. Required fields are marked *