Tutorialspoint
Problem
Solution
Submissions

Common Elements in Two Lists

Certification: Basic Level Accuracy: 71.79% Submissions: 39 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
ListMicrosoft
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 Counter to count occurrences in both lists.
  • Iterate through one list and check common counts in the other.

Steps to solve by this approach:

 Step 1: Use Counter to count occurrences of each element in both lists.

 Step 2: Initialize an empty list to store common elements.
 Step 3: Iterate through the elements in the first count dictionary.
 Step 4: Check if the element also exists in the second count dictionary.
 Step 5: If it exists in both, add it to the result list the minimum number of times it appears in either list. Step 6: Return the list of common elements including duplicates.

Submitted Code :