Data Structures · Sorting

std::set — course lists: de-duplicate, intersect, subtract, union

🗂 The two sets (unique + sorted) and the three result sets

element of a set (unique, sorted)result seti / j = the two pointers
both_courses (intersection)

🧾 Operation log

💬 Current step

💻 C++ (as the exercise asks)

Three key lines: set<int> s = {{...}} de-duplicates and sorts; set_intersection / set_difference / set_union all require sorted ranges and write through an inserter.

📄 Answers, complexity, pitfalls

1set.insert(v): duplicates ignored, order kept (red-black tree, O(log n) per insert)
2intersection: keep on equality, else advance the smaller side
3difference ds−os: keep ds-only values, skip both on a tie
4union: merge both runs, take equal values once
Courseware data and answers
Data Structures raw {1005, 1002, 1008, 1002, 1001, 1005} → set = {1001, 1002, 1005, 1008} (4 students, 2 duplicates dropped)
Operating Systems raw {1008, 1003, 1001, 1009, 1003} → set = {1001, 1003, 1008, 1009} (4 students, 1 duplicate dropped)
intersection both_courses = {1001, 1008}; difference only_ds = {1002, 1005}; union all_students = {1001, 1002, 1003, 1005, 1008, 1009}

Complexity: inserting n elements is O(n log n); intersection / difference / union each scan both sorted ranges once, O(n+m).
Why two pointers? Because a set keeps its elements sorted — that is the key difference from unordered_set (fast de-duplication but unordered, so an intersection would need sorting or hashing first).

Pitfalls: (1) the output of set_intersection must be able to insert — passing both_courses.begin() will not compile, use inserter(...); (2) the direction of the difference matters — set_difference(ds, os) is "only Data Structures"; (3) all three algorithms require sorted inputs, so sort a vector first.

📋 Courseware answers & how the three sets relate

setcontents (ascending)counthow
ds_students{1001, 1002, 1005, 1008}46 raw entries de-duplicated (2 dropped)
os_students{1001, 1003, 1008, 1009}45 raw entries de-duplicated (1 dropped)
both_courses{1001, 1008}2intersection ds ∩ os
only_ds{1002, 1005}2difference ds − os
all_students{1001, 1002, 1003, 1005, 1008, 1009}6union ds ∪ os

Check: |ds ∪ os| = |ds| + |os| − |ds ∩ os| = 4 + 4 − 2 = 6 ✓

Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result