Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Compare Arrays (Ignore Order)

Compare list contents while ignoring order using sorted. Students preserve duplicate counts and distinguish sorted-copy equality from comparing sets of values.

IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 2 of 10
compare-arrays-ignore-order.py
1# Take arrays
2n1 = int(input("Enter size of first array: "))
3arr1 = []
4for i in range(n1):
5 arr1.append(int(input(f"Array1 element {i+1}: ")))
6
7n2 = int(input("Enter size of second array: "))
8arr2 = []
9for i in range(n2):
10 arr2.append(int(input(f"Array2 element {i+1}: ")))
11
12# Compare ignoring order
13if sorted(arr1) == sorted(arr2):
14 print("Arrays contain same elements")
15else:
16 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

In this one

  • Ignore order while retaining counts
  • Use sorted copies
  • Distinguish sets from multisets

How it works

  1. 1

    Read the two lists.

  2. 2

    Sort copies of each with sorted.

  3. 3

    Compare those copies and print the content result.

Edge cases

Are duplicates ignored?

Are duplicates ignored?

No. Their counts must match.

Are original lists sorted in place?

Are original lists sorted in place?

No. sorted returns new lists.

What's going on

sorted creates an ordered copy of each list. Equality between those copies tests whether the same values occur with the same frequencies.

The original lists are unchanged. [1, 2, 1] and [2, 1, 1] match, but [1, 2] and [1, 1, 2] do not. Sorting removes the importance of original positions, not the importance of repeated entries.

Are duplicates ignored? No. Their counts must match.

Are original lists sorted in place? No. sorted returns new lists.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why not compare sets for this goal?

Pick an answer to check it.

Question 2

Are duplicates ignored?

Pick an answer to check it.

Questions people ask

Are duplicates ignored?

No. Their counts must match.

Are original lists sorted in place?

No. sorted returns new lists.

Why not compare sets for this goal?

Sets would discard duplicate counts.