0
0
Swiftprogramming~20 mins

Set algebra (union, intersection, difference) in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Set Algebra Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using set union?

Consider two sets of integers. What will be printed after performing a union?

Swift
let setA: Set<Int> = [1, 2, 3]
let setB: Set<Int> = [3, 4, 5]
let unionSet = setA.union(setB)
print(unionSet.sorted())
A[1, 2, 3, 4, 5]
B[1, 2, 4, 5]
C[3]
D[1, 2, 3]
Attempts:
2 left
💡 Hint

Union combines all unique elements from both sets.

Predict Output
intermediate
2:00remaining
What is the output of this Swift code using set intersection?

Find the common elements between two sets.

Swift
let setX: Set<Int> = [10, 20, 30, 40]
let setY: Set<Int> = [30, 40, 50, 60]
let intersectionSet = setX.intersection(setY)
print(intersectionSet.sorted())
A[30, 40]
B[10, 20, 30, 40, 50, 60]
C[50, 60]
D[10, 20]
Attempts:
2 left
💡 Hint

Intersection returns only elements present in both sets.

Predict Output
advanced
2:00remaining
What is the output of this Swift code using set difference?

Find elements in the first set that are not in the second set.

Swift
let setM: Set<Int> = [5, 10, 15, 20]
let setN: Set<Int> = [10, 20, 30]
let differenceSet = setM.subtracting(setN)
print(differenceSet.sorted())
A[30]
B[10, 20]
C[5, 15]
D[5, 10, 15, 20, 30]
Attempts:
2 left
💡 Hint

Difference removes elements of the second set from the first set.

🧠 Conceptual
advanced
1:30remaining
Which Swift set operation returns elements that are in either set but not in both?

Choose the correct set operation that returns elements exclusive to each set, excluding common elements.

Aintersection(_:)
BsymmetricDifference(_:)
Cunion(_:)
Dsubtracting(_:)
Attempts:
2 left
💡 Hint

Think about elements that are unique to each set, not shared.

Predict Output
expert
2:30remaining
What is the output of this Swift code combining multiple set operations?

Analyze the combined set operations and determine the final printed array.

Swift
let a: Set<Int> = [1, 2, 3, 4]
let b: Set<Int> = [3, 4, 5, 6]
let c: Set<Int> = [4, 5, 6, 7]
let result = a.union(b).intersection(c).subtracting([7])
print(result.sorted())
A[1, 2, 3]
B[3, 4]
C[5, 6, 7]
D[4, 5, 6]
Attempts:
2 left
💡 Hint

Break down the operations step-by-step: union, then intersection, then subtracting.