
Problem
Solution
Submissions
Intersection of Two Lists
Certification: Basic Level
Accuracy: 84.21%
Submissions: 38
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
Editorial
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. |
Solution Hints
- Use set intersection (
&
) to find common elements efficiently. - Convert lists to sets to remove duplicates before finding the intersection.