Elements in A Not in B

Find elements in first array not in second.

Logic BuildingIntermediate
Logic Building
# Take arrays
n1 = int(input("Enter size of first array: "))
arr1 = []
for i in range(n1):
    arr1.append(int(input(f"Array1 element {i+1}: ")))

n2 = int(input("Enter size of second array: "))
arr2 = []
for i in range(n2):
    arr2.append(int(input(f"Array2 element {i+1}: ")))

# Find elements in A not in B
result = []
for element in arr1:
    if element not in arr2 and element not in result:
        result.append(element)

print(f"Elements in A not in B: {result}")

Output

Enter size of first array: 4
Array1 element 1: 1
Array1 element 2: 2
Array1 element 3: 3
Array1 element 4: 4
Enter size of second array: 2
Array2 element 1: 2
Array2 element 2: 3
Elements in A not in B: [1, 4]

Find difference between arrays.

Key Concepts:

  • Check if element not in second array
  • Add to result if not present
  • Set difference operation