Count contributions and correct overlap
Group equal pairs and derive inclusion-exclusion by tracking how often one object is counted.
Understand the idea
If a value occurs f times, it contributes C(f, 2) unordered equal-value index pairs. Add over values. For two sets, |A ∪ B| = |A| + |B| − |A ∩ B| because intersection members were counted twice.
Trace a small example
Frequencies 3 and 2 contribute 3 + 1 = 4 equal pairs. For three sets, add singleton counts, subtract pair intersections, then add the triple intersection back: a member in all three was counted 3 − 3 + 1 = 1 time.
Conditions and cost
Intersections include members also present in further sets. Use wide arithmetic for f(f − 1)/2. A frequency scan is often faster and clearer than checking O(n²) pairs individually.
Frequency array
The value becomes an index. Each arrival increases freq[value] by one. This domain has ten possible values.
Input values
freq[value] — indices are values
The frequencies add up to 6, the number of input values.
Guided simulation · Change the inputs to test your understanding.
Why add the triple intersection back in three-set inclusion-exclusion?
Turn the idea into code
Among 30 students, 18 know C++, 12 know Python, and 7 know both. How many know neither?
Give me a hint
Find the union before subtracting it from the class.
Show the explained solution
The union has 18 + 12 − 7 = 23 students, so 30 − 23 = 7 know neither.
Your notes
Mark complete when you can explain it yourself.