6/28
Part 2 of 6 · Failures and retriesLearn and do

A failed task goes back in its original place

When a task fails, it goes back to waiting. But where in the line?

One candidate's report gives the rule: a task put back in the queue keeps the place of its original enqueue time. That candidate missed it, the unit tests didn't all pass, and the round was lost (1 report).

a, b and c were enqueued in that order. w2 holds b, and a fails.
right
ac
wrong
ca

a was enqueued before c, so it goes back ahead of c. Appended at the back, it would wait behind newer work.

A deque can only add at its two ends, so it can't do this. Appending sends a to the back. Adding at the front looks right with one failure and breaks with two. If a and b both fail, with b first, then a must still go before b.

The fix is to stop thinking of the line as arrival order. Give each task a number when it's first enqueued: 0, 1, 2, and so on. Keep the waiting tasks in a heap keyed by that number. A heap always gives you its smallest item, so the oldest waiting task comes out first. Putting a task back is one push with the number it already has.

A heap push and pop each cost O(log n), and the smallest item is heap[0]. If heaps are new to you, the heaps lesson builds one from a plain list.

ReadyLine in the editor is the waiting line inside the work queue, kept as a heap of (enqueue number, task id). Its enqueue and take work. Write put_back, which puts a failed task back by its original enqueue number.