Tutorialspoint
Problem
Solution
Submissions

Union of Two Lists

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

Write a Python program that finds the union of two lists. The output should be a list containing all unique elements from both lists.

Example 1
  • Input: list1 = [1, 2, 3], list2 = [3, 4, 5]
  • Output: [1, 2, 3, 4, 5]
  • Explanation:
    • Step 1: Create an empty result list to store unique elements.
    • Step 2: Create a set to track elements already added to the result.
    • Step 3: Iterate through the first list, adding each unique element to the result.
    • Step 4: Iterate through the second list, adding each unique element not already in the result.
    • Step 5: Return the result list containing all unique elements from both lists: [1, 2, 3, 4, 5].
Example 2
  • Input: list1 = [5, 5, 6], list2 = [6, 7, 8]
  • Output: [5, 6, 7, 8]
  • Explanation:
    • Step 1: Create an empty result list to store unique elements.
    • Step 2: Create a set to track elements already added to the result.
    • Step 3: Iterate through the first list, adding unique elements: [5, 6].
    • Step 4: Iterate through the second list, adding unique elements not already in the result: [5, 6, 7, 8].
    • Step 5: Return the result list containing all unique elements: [5, 6, 7, 8].
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 unique elements
ListPwCSnowflake
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 union (|) to find all unique elements.
  • Convert lists to sets before performing union.

Steps to solve by this approach:

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

 Step 2: Use the set union operator (|) to combine the elements from both sets.
 Step 3: Convert the resulting set back to a list.
 Step 4: Return the combined list with no duplicates.
 Step 5: Handle the case where both lists are empty by returning an empty list.

Submitted Code :