Union and Intersection of Two Arrays Using Hashing in Python

 

 

Program Overview

This Python program demonstrates how to find the union and intersection of two arrays using hashing. Hashing allows for efficient membership testing, which is utilized to identify common elements (intersection) and unique elements (union) between the two arrays.

Python Program


def find_union_and_intersection(arr1, arr2):
    """
    Find the union and intersection of two arrays using hashing.
    
    Args:
    arr1 (list): First array of integers.
    arr2 (list): Second array of integers.
    
    Returns:
    tuple: A tuple containing two sets - (union, intersection).
    """
    
    # Create a set for the union
    union_set = set()
    
    # Create a set for the intersection
    intersection_set = set()
    
    # Adding elements of the first array to the union set
    for num in arr1:
        union_set.add(num)
    
    # Adding elements of the second array to the union set
    for num in arr2:
        union_set.add(num)
        
    # Finding intersection
    for num in arr1:
        if num in arr2:
            intersection_set.add(num)
    
    return union_set, intersection_set


# Example usage
if __name__ == "__main__":
    array1 = [1, 2, 3, 4, 5]
    array2 = [4, 5, 6, 7, 8]
    
    union, intersection = find_union_and_intersection(array1, array2)
    
    print("Union:", union)
    print("Intersection:", intersection)

Program Structure Explanation

The program consists of the following components:

  1. Function Definition:The function find_union_and_intersection(arr1, arr2) takes two arrays as input arguments.
  2. Union Set:A set named union_set is created to store all unique elements from both arrays.
  3. Intersection Set:A set named intersection_set is created to store common elements between the two arrays.
  4. Looping Through Arrays:Two loops are used: the first to add all elements from both arrays to the union set, and the second to check for common elements, adding them to the intersection set.
  5. Return Values:The function returns a tuple containing the union and intersection sets.
  6. Example Usage:An example usage of the function demonstrates how to call it and print the results.

Conclusion

This program effectively utilizes hashing to compute the union and intersection of two arrays in an efficient manner. Hash sets allow for O(1) average-time complexity for membership tests, making the solution scalable for larger datasets.

 

Leave a Reply

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