Finding Arrays are Disjoint or Not in Python
Understanding Disjoint Arrays
Two arrays are said to be disjoint if they have no elements in common.
We will explore three different methods to check if two arrays are disjoint in Python.
Method 1: Using Nested Loops
This method iterates through both arrays and checks for common elements.
def are_disjoint(arr1, arr2): for i in arr1: for j in arr2: if i == j: return False return True arr1 = [1, 2, 3, 4] arr2 = [5, 6, 7, 8] if are_disjoint(arr1, arr2): print("Arrays are disjoint") else: print("Arrays are not disjoint")
Arrays are disjoint
Method 2: Using Hashing
This method uses a set to check for common elements efficiently.
def are_disjoint(arr1, arr2): hash_set = set(arr1) for num in arr2: if num in hash_set: return False return True arr1 = [1, 2, 3, 4] arr2 = [5, 6, 7, 8] if are_disjoint(arr1, arr2): print("Arrays are disjoint") else: print("Arrays are not disjoint")
Arrays are disjoint
Method 3: Using Set Intersection
This method uses set operations to determine if two arrays are disjoint.
def are_disjoint(arr1, arr2): return len(set(arr1) & set(arr2)) == 0 arr1 = [1, 2, 3, 4] arr2 = [5, 6, 7, 8] if are_disjoint(arr1, arr2): print("Arrays are disjoint") else: print("Arrays are not disjoint")
Arrays are disjoint