Skip to content

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.

def has_common_integer(a, b):
    return bool(a & b)

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:

Call
has_common_integer({1, 2, 3}, {3, 4, 5})
Output
True
Call
has_common_integer({10, 20}, {30, 40})
Output
False
Call
has_common_integer({7, 8}, {8, 9})
Output
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

def has_common_integer(a: set, b: set) -> bool:
    common = a & b          # intersection: elements in both sets
    return len(common) > 0  # True if at least one common element
def has_common_integer(a: set, b: set) -> bool:
    return bool(a & b)      # empty set is falsy, non-empty is truthy
has_common_integer = lambda a, b: not a.isdisjoint(b)

Key takeaways

01

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.

02

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?"

03

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.