Beyond Big O

Retrying job queue

Retrying job queue

Medium

Solution guide

Reveal solution guide — spoilers

Approach

  1. Store all accepted IDs in a permanent identity map, with each active job’s payload, state and latest attempt. Track active count separately from the waiting FIFO.
  2. Reserve from the waiting head, mark the job in flight and increment that job’s attempt. Accept Ack or Retry only when both the in-flight state and attempt token match; Retry appends to the waiting tail without freeing capacity.
  3. Ack and Cancel release an active capacity slot while retaining the accepted ID as a tombstone. Remove or skip cancelled waiting entries while preserving the order of remaining jobs. Keep every queue instance independent.

Why it works

The active counter includes both waiting and in-flight jobs, so reservation cannot create capacity. State plus attempt identity fences late acknowledgements from earlier reservations. Retaining accepted IDs prevents a completed job from being silently replaced, and appending retries preserves the specified FIFO order.

Complexity

With an ID map and a linked waiting queue, enqueue, reserve, acknowledge, retry and cancel use expected O(1) time. A simpler array/list implementation may need O(Q) removal or scanning. Storage is O(U) for U accepted IDs, including terminal tombstones.

Edge cases to check

  • Capacity zero rejects every enqueue. A full queue must not reserve a rejected ID, so enqueueing it after capacity frees can succeed.
  • An in-flight job occupies capacity even when Reserve returns no waiting job.
  • A stale attempt cannot acknowledge a retried reservation, and cancelled/completed IDs cannot be reused.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…