Learn
You only looked up a key in your defaultdict, and now the key is there
You keep a map from a key to a list, and somewhere else you ask "is this key in the map?" as a quick way of asking "does this key have anything?". The two questions agree on every example you try. Then one read, or one removal of the last item, makes them disagree, and the bug shows up far from the line that caused it.
The situation
A help desk keeps open tickets per agent, oldest first. It needs to assign a ticket, close an agent's oldest ticket, peek at it, and count how many agents are busy. A natural first version in Python uses defaultdict, because it saves the "create the queue if it is missing" step:
from collections import defaultdict, deque
class Desk:
def __init__(self):
self.queues = defaultdict(deque) # agent -> open tickets
def assign(self, agent, ticket):
self.queues[agent].append(ticket)
def close_oldest(self, agent):
return self.queues[agent].popleft()
def oldest(self, agent):
q = self.queues[agent]
return q[0] if q else None
def busy_agents(self):
return len(self.queues)
Every test that assigns first and then counts passes.
The input that exposes it
Two calls are enough. On a new desk, call oldest("a1"). It returns None, which is right. Now call busy_agents(). It returns 1, and nobody has a ticket.
The reason is that self.queues[agent] on a defaultdict is not only a read. When the key is missing, it calls the factory, stores an empty deque under that key and returns it. A method that was meant to look has written.
The second path is just as quiet: assign("a1", 7), then close_oldest("a1"), then busy_agents(). It returns 1 again. The deque is empty, but the key stays.
The hidden assumption is a key in the map means the key has items. Nothing in the code enforces it. Java has the same trap: computeIfAbsent(agent, k -> new ArrayDeque<>()) inside a read method inserts an empty queue, and polling the last ticket leaves the empty queue in the map. The same bug turns up in order books, where a price level emptied by a trade stays in the map and later code wrongly trusts it.
There is a cost beyond the wrong count. In a long-running service, every id anyone ever looked up, including a mistyped one, now holds an entry. The map grows with reads, not with work.
The invariant
State one rule and make every path keep it: an agent is a key exactly when their queue is not empty. That means two things. Reads never create keys, so they use get, which does not call the factory. Any removal that empties a queue deletes the key in the same step.
def close_oldest(self, agent):
q = self.queues.get(agent)
if not q:
return None
ticket = q.popleft()
if not q:
del self.queues[agent]
return ticket
def oldest(self, agent):
q = self.queues.get(agent)
return q[0] if q else None
Keep self.queues[agent] only in assign, where creating the key is the point. Now oldest("a1") then busy_agents() gives 0, and assign, close, count gives 0.
In Java the removal reads the same way:
Integer closeOldest(String agent) {
Deque<Integer> q = queues.get(agent);
if (q == null) return null;
Integer ticket = q.pollFirst();
if (q.isEmpty()) queues.remove(agent);
return ticket;
}
The other honest option is to drop the rule: let empty queues stay and count sum(1 for q in self.queues.values() if q). That is correct, but the count is now linear in every agent ever seen, and the growth problem remains. If you choose it, say why.
What to say out loud
When you write the map, say its rule before the first method: "A key is in this map only while its queue has something in it. I will create keys only when I add, and delete the key when I remove the last item."
When you write a read, say which call you use and why: "I will use get here, because indexing a defaultdict would insert an empty queue."
Then name the input that would catch you: "If I got this wrong, peeking at a new agent and then counting would show it, so I will trace that."
The exercise
- Type the first version above, call
oldest("a1")thenbusy_agents(), and predict the answer before you run it. - Find every line in the class that indexes the map, and mark each one as "adds" or "reads". Change every "reads" to
get. - Add the delete on the emptying path and trace assign, close, count by hand.
- Write the Java version with
getandremove, and say whycomputeIfAbsentbelongs only inassign. - Look through your last month of code for a membership check on a map of lists, and write down the rule it relies on.
Where this fits in Gadfly
Gadfly has four rooms, and in the algorithms room you code in Java or Python. Hash maps are not one of its four authored pattern lessons; they are practised through its catalog of 711 problems, each tagged by the pattern it trains. In tutor mode it asks the next question rather than revealing the solution, so "which lines in this class can add a key?" is the kind of question it puts to you, and "I'm stuck" gives one more step, up to pseudocode, never finished code. In mock mode it behaves like an interviewer and gives no coaching during the round, then a debrief quoted from the session record.
Published 28 November 2026 · One mistake, one counterexample · all notes · feed
This note was drafted by Gadfly's scout — an automated writing agent run by Dmytro Hryshchenko — and checked by rules against the product's claims registry, not read by a person before it went live. The exercise is original. Spotted a mistake? [email protected].