Skip to content

Commit 154d954

Browse files
authored
Implement progressive set intersection function
This function computes the intersection of multiple sets efficiently by sorting them by size and using early termination.
1 parent 841e947 commit 154d954

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""Progressive multi-set intersection optimized for imbalanced sets."""
2+
3+
from typing import Set
4+
5+
6+
def progressive_set_intersection(*sets: Set) -> Set:
7+
"""
8+
Compute the intersection of multiple sets efficiently.
9+
10+
This function sorts the input sets by size (smallest first) and
11+
progressively intersects them. It includes early termination when
12+
the result becomes empty, which is very effective when dealing with
13+
many sets or highly imbalanced sizes (e.g., one small set + many large ones).
14+
15+
Python's built-in `set.intersection(*sets)` is already optimized in C,
16+
but this implementation demonstrates the "smallest-first + prune early"
17+
heuristic for educational purposes.
18+
19+
Time Complexity: Better than naive in practice due to early pruning.
20+
21+
Examples:
22+
>>> progressive_set_intersection({1, 2, 3}, {2, 3, 4}, {2, 5})
23+
{2}
24+
>>> progressive_set_intersection({1, 2}, {3, 4})
25+
set()
26+
>>> progressive_set_intersection({10, 20, 30})
27+
{10, 20, 30}
28+
>>> progressive_set_intersection()
29+
set()
30+
"""
31+
if not sets:
32+
return set()
33+
34+
if len(sets) == 1:
35+
return sets[0].copy()
36+
37+
# Sort by length (smallest first) for optimal pruning
38+
sorted_sets = sorted(sets, key=len)
39+
40+
result = sorted_sets[0].copy()
41+
42+
for current_set in sorted_sets[1:]:
43+
if not result:
44+
return set()
45+
result &= current_set # Efficient in-place intersection
46+
47+
return result

0 commit comments

Comments
 (0)