Python List Advanced Exercise - Find the union and intersection of two lists
7. Union and Intersection of Two Lists
Write a Python a function to find the union and intersection of two lists.
Sample Solution:
Python Code:
Sample Output:
Original lists: [1, 2, 3, 4, 5] [3, 4, 5, 6, 7, 8] Union of said two lists: [1, 2, 3, 4, 5, 6, 7, 8] Intersection of said two lists: [3, 4, 5] Original lists: ['Red', 'Green', 'Blue'] ['Red', 'White', 'Pink', 'Black'] Union of said two lists: ['Pink', 'Blue', 'White', 'Black', 'Red', 'Green'] Intersection of said two lists: ['Red']
Flowchart:

What is the time complexity and space complexity of the following Python code?
Time complexity - The time complexity of the said code is O(n), where n is the combined length of "lst1" and "lst2". The set() function is used to remove duplicates from the input lists, which takes O(n) time in the worst case. The | and & operators are used to compute the union and intersection of the two sets "lst1" and "lst2", which also takes O(n) time in the worst case.
Space complexity – The space complexity of this code is also O(n), since two new lists "union" and "intersection" are created to store the union and intersection of the input lists "lst1" and "lst2". In addition, two sets (set(lst1) and set(lst2)) are also created to store the unique elements of "lst1" and "lst2". The space used by these sets depends on the number of unique elements in the input lists and is typically less than the total length of the lists. In the worst case, where there are no duplicates, the space complexity is O(n).
For more Practice: Solve these Related Problems:
- Write a Python function to return the union of two lists without duplicates using set operations.
- Write a Python function to compute the intersection of two lists and return a sorted list of common elements.
- Write a Python function to calculate both union and intersection of two lists without converting them to sets.
- Write a Python function to merge two lists and then determine their union and intersection using a dictionary to count occurrences.
Go to:
Previous: Check if a list is a palindrome or not.
Next: Preserve order by removing duplicates.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.