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

Count Common Elements

Count distinct common values with set intersection. Students distinguish shared value types from matching positions and repeated occurrences in either input list.

IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 6 of 10
count-common-elements.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# Count common
13common_set = set(arr1) & set(arr2)
14count = len(common_set)
15
16print(f"Number of common elements: {count}")

Output

Enter size of first array: 4
Array1 element 1: 1
Array1 element 2: 2
Array1 element 3: 3
Array1 element 4: 2
Enter size of second array: 3
Array2 element 1: 2
Array2 element 2: 3
Array2 element 3: 4
Number of common elements: 2

In this one

  • Intersect sets
  • Count distinct shared values
  • Discard multiplicity deliberately

How it works

  1. 1

    Convert both lists into sets.

  2. 2

    Intersect them with &.

  3. 3

    Print the size of the resulting common set.

Edge cases

Are repetitions counted separately?

Are repetitions counted separately?

No. Sets retain distinct values.

What if there is no shared value?

What if there is no shared value?

The intersection is empty and the count is zero.

What's going on

set(arr1) and set(arr2) each retain one copy of a value. The & operator forms their intersection.

len(common_set) counts those distinct shared values. If two appears three times in each list, it contributes one, not three or nine. No set order is relied on because only its size is printed. Either empty input yields zero.

Are repetitions counted separately? No. Sets retain distinct values.

What if there is no shared value? The intersection is empty and the count is zero.

Quiz

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

Question 1

What does & mean for these sets?

Pick an answer to check it.

Question 2

Are repetitions counted separately?

Pick an answer to check it.

Questions people ask

Are repetitions counted separately?

No. Sets retain distinct values.

What if there is no shared value?

The intersection is empty and the count is zero.

What does & mean for these sets?

Intersection.