
Problem
Solution
Submissions
Common Elements in Two Lists
Certification: Basic Level
Accuracy: 70%
Submissions: 40
Points: 10
Write a Python program that finds common elements in two lists, considering duplicates.
Example 1
- Input: list1 = [1, 2, 2, 3], list2 = [2, 2, 3, 4]
- Output: [2, 2, 3]
- Explanation:
- Step 1: Create a dictionary to count occurrences of each element in the first list.
- Step 2: Create an empty result list to store common elements.
- Step 3: Iterate through the second list, checking if each element exists in the dictionary.
- Step 4: If the element exists and has a count > 0, add it to the result and decrement its count.
- Step 5: Return the common elements with correct multiplicity: [2, 2, 3].
Example 2
- Input: list1 = [1, 2, 3], list2 = [4, 5, 6]
- Output: []
- Explanation:
- Step 1: Create a dictionary to count occurrences of each element in the first list.
- Step 2: Create an empty result list to store common elements.
- Step 3: Iterate through the second list, checking if each element exists in the dictionary.
- Step 4: No common elements are found between the two lists.
- Step 5: 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 frequency counter dictionary
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
Counter
to count occurrences in both lists. - Iterate through one list and check common counts in the other.