Skip to contentKEEP THE CRAFTTHE SANCTUARY

Hash Set

Use a Python set when the state is presence rather than a count or attached value. Define which equality classes are stored and when an occurrence becomes seen, then choose membership, removal, or set algebra deliberately.

9 practice exercises12 interview problems

Recognize it when Repeated questions ask whether a value belongs to the processed prefix.

Checking your account…

Hash Set Code Labs

Mental Model

A set answers whether a distinct hashable value is present. It deliberately stores no attached count, index, or payload. This narrower contract makes intent clearer than a dictionary whose values are meaningless placeholders.

Presence Without Attached Values

Python set supports expected O(1) membership, insertion, and removal under ordinary hashing. Keys must be hashable and keep stable equality/hash behavior while stored. Lists and sets are mutable and cannot be members; use a tuple or frozenset only when that immutable representation matches the problem’s equality rule.

The set documentation(opens in a new tab) defines add, discard, remove, and algebra operations. discard tolerates absence; remove raises KeyError when absence violates the contract.

Track Seen State in One Pass

Test membership before insertion when the output asks whether a value appeared earlier. The invariant is that seen contains exactly the distinct values from the processed prefix. Inserting first would make every current value appear duplicated by itself.

Flag Previously Seen Values

Reference
def track_seen_values(values):
    seen = set()
    result = []
    for value in values:
        result.append(value in seen)
        seen.add(value)
    return result
Practice

Implement track_seen_values(values). Return true exactly when the current value appeared at an earlier index, before adding the current occurrence.

Public tests

  • Verify earlier occurrence semantics

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Flag Previously Seen Values

def track_seen_values(values):
    seen = set()
    result = []
    for value in values:
        result.append(value in seen)
        seen.add(value)
    return result

Trace the Moment a Value Becomes Seen

Run the existing earlier-occurrence Lab with a repeated value. A first occurrence produces False even though it will become a member immediately afterward. The set tracks the processed prefix, not every value in the whole input.

print(track_seen_values([5, 5, 2, 5])) followed by print(track_seen_values([]))

Step Executed statement State Why
1 seen = set(); result = [] seen = set(); result = [] The empty processed prefix contains no values.
2 result.append(value in seen); seen.add(value) value = 5; result = [False]; seen = {5} The membership question is answered before the first insertion.
3 result.append(value in seen); seen.add(value) value = 5; result = [False, True]; seen = {5} The earlier 5 exists; reinsertion does not add another member.
4 result.append(value in seen); seen.add(value) value = 2; result = [False, True, False]; seen = {2, 5} A new equality class extends the prefix state.
5 result.append(value in seen); return result value = 5; result = [False, True, False, True] Any earlier occurrence is sufficient; counts would store unnecessary state.
Print Output
1 [False, True, False, True]
2 []

A set deliberately loses multiplicity; it is enough here because each answer is a presence question. Query-before-insert supplies the time boundary that makes the same membership operation answer ‘earlier’ rather than ‘now’.

Apply Set Algebra

Intersection expresses “in both,” difference expresses “only on this side,” and union expresses “in either.” These operations return sets and therefore discard duplicates and sequence order. Convert to a sorted list only when the output contract needs deterministic ordering.

Compute Set Relationships

Reference
def set_relationships(left, right):
    left_set = set(left)
    right_set = set(right)
    return (
        sorted(left_set & right_set),
        sorted(left_set - right_set),
        sorted(left_set | right_set),
    )
Practice

Implement set_relationships(left, right). Return sorted shared values, values only on the left, and the full union as a tuple of lists. All input members are hashable and mutually sortable.

Public tests

  • Verify intersection difference union

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Set Relationships

def set_relationships(left, right):
    left_set = set(left)
    right_set = set(right)
    return (
        sorted(left_set & right_set),
        sorted(left_set - right_set),
        sorted(left_set | right_set),
    )

Predict Equality, Hashability, and Display Order

Predict the number of members before expecting three numeric values. Python numeric equality makes 1, 1.0, and True equal, with compatible hashes, so the set contains one distinct value. This example deliberately prints the size rather than assuming which representation survives. For the pair display, every element has the same comparable tuple shape, so sorting gives a deterministic result.

Line Python statement Observation
1 members = {1, 1.0, True} Equal numeric values collapse.
2 print(len(members)) Count distinct equality classes.
3 pairs = {(2, 3), (1, 4)} Use hashable integer tuples.
4 print(sorted(pairs)) Display comparable members deterministically.
5 try: Start the expected-error probe.
6 members.add([2, 3]) Try body: a mutable list is not hashable.
7 except TypeError: Handle that precise boundary.
8 print("list is not hashable") Except body: make the expected failure visible.
9 members.add((2, 3)) Use the corresponding hashable pair.
10 print((2, 3) in members) Confirm membership.

Expected printed output:

Print Output
1 1
2 [(1, 4), (2, 3)]
3 list is not hashable
4 True

The caught error is an expected boundary: a mutable list cannot become a set member. A tuple is suitable here because both of its integer elements are hashable; a tuple containing a list would still fail. If the problem treats booleans and integers as different labels, normalize or tag the keys explicitly rather than relying on a set to preserve that distinction. Do not treat raw set display as an ordering contract. Sorting k comparable members adds O(k log k) work and O(k) output storage; it belongs in the output-cost explanation, not inside a hot membership loop.

Choose set or dict

Use a set for presence, deduplication, visited state, and algebra. Use a dictionary when each key must retain a count, original index, predecessor, or computed value. Use a boolean list when the key domain is small and dense; it may be faster and makes the bounded domain explicit.

Set Membership and Ordering Mistakes

  • Using a mutable list as a member raises TypeError; choose an immutable semantic key.
  • Depending on set iteration order creates unstable output even if one run looks consistent.
  • Removing while iterating the same set can raise a runtime error.
  • Building set(values) too early loses duplicate positions and encounter order.
  • Claiming worst-case O(1) ignores collision behavior and the cost of hashing long keys.

Explain It in an Interview

State exactly what membership means and why no payload is needed. Define when a value enters the set and whether input order must survive. Give expected O(1) operations and O(n) space, while noting that hashing a compound key includes the work needed to hash its contents.

Track Previously Seen Values(opens in a new tab) isolates the prefix invariant. Design HashSet(opens in a new tab) then asks you to implement collision-safe membership without relying on the built-in set.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Hash Set itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Membership, insertion or removalO(1)O(n)n stored members; ordinary hashing gives expected constant-time operations, but collision behavior can degrade them.
Flag a length-m input sequenceO(m)O(m * n)Includes returned flags and distinct seen members; hashing/equality cost of the chosen keys is additional.

Space

O(n) stored members and O(1) extra working space per membership/update; O(m + n) including returned flags for a length-m scan.

Assumptions

  • n stored members; ordinary hashing gives expected constant-time operations, but collision behavior can degrade them.
  • Includes returned flags and distinct seen members; hashing/equality cost of the chosen keys is additional.

Invariants Worth Saying Aloud

  1. Before processing index i, seen contains exactly distinct values from earlier positions.
  2. Query earlier membership before adding the current occurrence.
  3. Every stored member is hashable with stable equality and hash behavior.

When To Use Or Avoid Hash Set

Use It When

  • Store visited values or presence state with expected constant-time lookup.
  • Use set algebra when duplicates and encounter order may be discarded.

Choose Another Tool When

  • Use a dictionary when a member needs a count, index or payload.
  • Use a boolean list for a small dense bounded integer domain.
  • Keep a sequence when duplicate positions or encounter order belong to the answer.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Recording the current occurrence before asking about the past

Adding first makes a new value match itself. The membership query must refer to the processed prefix before this occurrence.

Prevent it: Answer the query, then add the current value.

Avoid

seen.add(value)
was_seen = value in seen

Use instead

was_seen = value in seen
seen.add(value)

Choosing removal that rejects a valid absence

remove raises KeyError for an absent value. That is useful only when absence is an error; optional removal should tolerate it.

Prevent it: Use discard when 'ensure absent' is the required operation.

Avoid

seen.remove(value)

Use instead

seen.discard(value)

Using a mutable coordinate as a member

A list coordinate cannot be hashed. The integer tuple keeps the same ordered coordinate meaning and is hashable.

Prevent it: Represent a coordinate with a tuple of hashable components.

Avoid

seen.add([row, column])

Use instead

seen.add((row, column))

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.