
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
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 union (
|
) to find all unique elements. - Convert lists to sets before performing union.