Tutorialspoint
Problem
Solution
Submissions

Intersection of Two Lists

Certification: Basic Level Accuracy: 84.62% Submissions: 39 Points: 5

Write a Python program that finds the common elements between two lists. The output should be a list containing elements that appear in both lists.

Example 1
  • Input: list1 = [1, 2, 3, 4], list2 = [3, 4, 5, 6]
  • Output: [3, 4]
  • Explanation:
    • Step 1: Create a set from the first list for O(1) lookups.
    • Step 2: Iterate through the second list, checking if each element exists in the set.
    • Step 3: If an element is found in both lists, add it to the result list.
    • Step 4: The elements 3 and 4 appear in both lists, so return [3, 4].
Example 2
  • Input: list1 = [10, 20, 30], list2 = [40, 50, 60]
  • Output: []
  • Explanation:
    • Step 1: Create a set from the first list for O(1) lookups.
    • Step 2: Iterate through the second list, checking if each element exists in the set.
    • Step 3: No common elements are found between the two lists.
    • Step 4: Return an empty list [].
Constraints
  • 1 ≤ len(list1), len(list2) ≤ 10^3
  • -10^5 ≤ list1[i], list2[i] ≤ 10^5
  • Time Complexity: O(n) where n is the total number of elements in both lists
  • Space Complexity: O(n) to store the elements from the first list in a set
ListEYDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use set intersection (&) to find common elements efficiently.
  • Convert lists to sets to remove duplicates before finding the intersection.

Steps to solve by this approach:

 Step 1: Convert both input lists to sets to eliminate duplicates.

 Step 2: Use the set intersection operator (&) to find common elements.
 Step 3: Convert the resulting set back to a list.
 Step 4: Return the list of common elements.
 Step 5: Handle the case where there are no common elements by returning an empty list.

Submitted Code :