S1Q2 · Check for Common Integer¶
⚡ Quick Reference
Function: has_common_integer(a: set, b: set) -> bool
Core idea: Set intersection -- non-empty means at least one common element exists.
Key rules:
- a & b is the intersection of the two sets
- An empty set is falsy; a non-empty set is truthy
- bool() converts the result to True or False
Problem Statement¶
Problem
Write a function has_common_integer(a, b) that takes two sets of integers and returns True if they share at least one element, False otherwise.
Examples:
has_common_integer({1, 2, 3}, {3, 4, 5})
True
has_common_integer({10, 20}, {30, 40})
False
has_common_integer({7, 8}, {8, 9})
True
Understanding the problem¶
Set intersection (&) produces a new set containing only the elements present in both sets:
a |
b |
a & b |
Non-empty? | Result |
|---|---|---|---|---|
{1,2,3} |
{3,4,5} |
{3} |
✅ | True |
{10,20} |
{30,40} |
{} |
✗ | False |
{7,8} |
{8,9} |
{8} |
✅ | True |
Empty sets are falsy in Python
bool(set()) is False; bool({3}) is True. So bool(a & b) converts the intersection directly to the answer -- no need to check len() or compare to set().
Two equivalent alternatives
a.isdisjoint(b) returns True when sets have NO common elements. So not a.isdisjoint(b) also works and is slightly more readable in plain English: "they are not disjoint". Both approaches are O(min(len(a), len(b))).
Solution approaches¶
Key takeaways¶
Set intersection: a & b or a.intersection(b)
Both forms produce the set of elements common to a and b. The & operator is more concise; .intersection() also accepts any iterable, not just sets.
Truthiness of sets
An empty set set() is falsy; any non-empty set is truthy. Wrapping in bool() converts the intersection result directly to the answer -- a common idiom for "does this collection have anything?"
set.isdisjoint() for the "no overlap" check
a.isdisjoint(b) returns True when sets share no elements. It short-circuits on the first common element found, making it efficient. Negate it (not a.isdisjoint(b)) to check for any overlap.