Day 20 – Set Operations Problems

In Python, sets are a powerful data structure for handling unique items and performing mathematical operations like union, intersection, and difference. Mastering set operations is essential for solving interview questions related to collections, duplicates, and comparisons.

Problem 1: Union of Two Sets

Problem Statement: Write a program to find the union of two sets.

Example:

Input: A = {1, 2, 3}, B = {3, 4, 5}
Output: {1, 2, 3, 4, 5}

Problem 2: Intersection of Two Sets

Problem Statement: Find the common elements between two sets.

Example:

Input: A = {1, 2, 3}, B = {2, 3, 4}
Output: {2, 3}

Problem 3: Subset Check

Problem Statement: Check if one set is a subset of another.

Example:

Input: A = {1, 2}, B = {1, 2, 3, 4}
Output: True

Problem 4: Symmetric Difference

Problem Statement: Find elements that are in either set but not in both.

Example:

Input: A = {1, 2, 3}, B = {3, 4, 5}
Output: {1, 2, 4, 5}

Problem 5: Remove Duplicates from List

Problem Statement: Remove duplicates from a list using sets.

Example:

Input: [1, 2, 2, 3, 4, 4, 5]
Output: {1, 2, 3, 4, 5}

Problem 6: Common Elements in Multiple Sets

Problem Statement: Find elements that are common across three sets.

Example:

Input: A = {1,2,3}, B = {2,3,4}, C = {3,4,5}
Output: {3}

Problem 7: Compare Sets for Equality

Problem Statement: Check if two sets contain the same elements.

Example:

Input: A = {1, 2, 3}, B = {3, 2, 1}
Output: True

Problem 8: Unique Elements Count

Problem Statement: Count the number of unique elements in a collection.

Example:

Input: [1, 2, 2, 3, 4, 4, 5]
Output: 5

Problem 9: Real-world Example – Common Skills

Problem Statement: Given two job applicants’ skill sets, find their common skills.

Example:

Input: A = {"Python", "SQL", "Git"}, B = {"Python", "Java", "Git"}
Output: {"Python", "Git"}

Problem 10: Real-world Example – Unique Visitors

Problem Statement: From a website log containing visitor IDs, find the unique visitors.

Example:

Input: [101, 102, 101, 103, 104, 102]
Output: {101, 102, 103, 104}