Compare Arrays (Ignore Order)

Check if arrays contain same elements ignoring order.

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}: ")))

# Compare ignoring order
if sorted(arr1) == sorted(arr2):
    print("Arrays contain same elements")
else:
    print("Arrays contain different elements")

Output

Enter size of first array: 3
Array1 element 1: 1
Array1 element 2: 2
Array1 element 3: 3
Enter size of second array: 3
Array2 element 1: 3
Array2 element 2: 1
Array2 element 3: 2
Arrays contain same elements

Sort both arrays and compare.

Key Concepts:

  • Sort both arrays
  • Compare sorted versions
  • Ignores original order