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

Find Common Elements

Find distinct values shared by two lists. Students combine membership with duplicate suppression and preserve first-list order in the common-value result.

IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 4 of 10
find-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# Find common elements
13common = []
14for element in arr1:
15 if element in arr2 and element not in common:
16 common.append(element)
17
18print(f"Common elements: {common}")

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
Common elements: [2, 3]

In this one

  • Find shared values
  • Suppress duplicate output
  • Preserve first-list ordering

How it works

  1. 1

    Visit each value in arr1.

  2. 2

    Require membership in arr2 and absence from common.

  3. 3

    Append qualifying values once and print common.

Edge cases

Do repeated shared values appear twice?

Do repeated shared values appear twice?

No. common suppresses repeated output.

What if either list is empty?

What if either list is empty?

There are no shared values.

What's going on

The loop scans arr1. A value is appended only if it exists in arr2 and has not already been placed in common.

The second test prevents duplicate output when arr1 repeats a shared value. The result follows first appearance in arr1 rather than sorted order. This uses list membership searches, so larger inputs can require repeated scans.

Do repeated shared values appear twice? No. common suppresses repeated output.

What if either list is empty? There are no shared values.

Quiz

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

Question 1

Which list determines result order?

Pick an answer to check it.

Question 2

Do repeated shared values appear twice?

Pick an answer to check it.

Questions people ask

Do repeated shared values appear twice?

No. common suppresses repeated output.

What if either list is empty?

There are no shared values.

Which list determines result order?

arr1.