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)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…
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.
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.
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.
def track_seen_values(values):
seen = set()
result = []
for value in values:
result.append(value in seen)
seen.add(value)
return resultImplement track_seen_values(values). Return true exactly when the current value appeared at an earlier index, before adding the current occurrence.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def track_seen_values(values):
seen = set()
result = []
for value in values:
result.append(value in seen)
seen.add(value)
return resultRun 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. |
| 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’.
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.
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),
)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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 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:
| 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.
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.
TypeError; choose an immutable semantic key.set(values) too early loses duplicate positions and encounter order.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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Membership, insertion or removal | O(1) | O(n) | n stored members; ordinary hashing gives expected constant-time operations, but collision behavior can degrade them. |
| Flag a length-m input sequence | O(m) | O(m * n) | Includes returned flags and distinct seen members; hashing/equality cost of the chosen keys is additional. |
O(n) stored members and O(1) extra working space per membership/update; O(m + n) including returned flags for a length-m scan.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
seen.add(value)
was_seen = value in seenwas_seen = value in seen
seen.add(value)Where you will hit this: Track Previously Seen Values(opens in a new tab)
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.
seen.remove(value)seen.discard(value)Where you will hit this: Track Previously Seen Values(opens in a new tab)
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.
seen.add([row, column])seen.add((row, column))Where you will hit this: Design HashSet(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27