InterviewLegend

Staged Simulations

Alex Chen18 min readGuide updated
In this lesson
  • Build Instacart's multi-stage prompts so each new stage is an added method over the same state
  • Hold arrival order in a deque so the bus route's priority pass breaks ties the same way every run
  • Store raw intervals and per-task histories instead of running totals, so rate changes and as-of reads stay cheap
  • Fire scheduled payouts from a min-heap in due order, with every amount in integer cents

Staged simulations are some of the most solved Instacart prompts. Each one is a small system that grows in stages, like a bus route that adds a waitlist and a priority pass, a payroll tracker that turns clock-in pairs into cents, a fulfillment task manager on a logical clock, or a ledger that schedules payouts. Each opens with two or three methods and the provided tests. Then the interviewer adds a method or a business rule, much like the four levels of the CodeSignal assessment, so the state you choose in stage one decides how hard stage three is.

Naming the state first and choosing the map for the query you can see coming are covered in Hash Maps & Design.

Asked at Instacart

1

Bus Route Simulation: Boarding, Capacity, Priority in Stages

MediumSignature problem
Problem
Build a bus route simulation that grows in stages: boarding, capacity, then a priority pass. A bus with a fixed number of seats runs an ordered list of stops. Riders board where a seat is free, get off where they like, and the ones who could not board wait for the next stop. Build the simulation in three stages, each adding methods to the same BusRoute(capacity) object. Riders are string ids.

Stage 1, boarding and capacity.
- board(rider): a walk-up at the current stop. Return True and seat the rider when a seat is free, nobody is waiting in a line, and the rider is not already aboard or in a line. Otherwise return False and change nothing.
- alight(rider): return True and free the seat if the rider is aboard, otherwise False.

Stage 2, the waitlist.
- join(rider): the rider joins the regular line. Ignore a rider who is already aboard or already in a line.
- arrive(): the bus pulls into the next stop. Waiting riders board in arrival order while seats remain. Return the riders who boarded at this stop, in boarding order, or an empty list.

Stage 3, the priority pass.
- priority(rider): the rider joins the priority line, with the same duplicate rule as join. At each stop, priority riders board ahead of the regular line, with one guard against starving it. When the regular line is not empty, its longest-waiting rider takes the first free seat. The remaining seats go to priority riders in arrival order, then to regular riders in arrival order.
  1. BusRoute(1)
  2. board("A")→ true
  3. join("B")
  4. arrive()→ []
  5. alight("A")→ true
  6. arrive()→ ["B"]

A takes the only seat. B joins the line, and the first stop boards nobody because the bus is full. Once A alights the seat is free, so the next stop boards B.

How this uses the pattern

A set for who is aboard plus two deques for the lines, and one more set so the duplicate check across all three places is O(1). Capacity is a count against the aboard set. Each stop drains the lines in a fixed order, one reserved seat for the regular head, then the priority line, then the rest of the regular line.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Bus Route Simulation: Boarding, Capacity, Priority in Stages

Loading...
Click "Run" to execute your code
The Instacart angle
The bus is a batching problem in simple form, plus a priority pass that works like a paid priority-delivery tier. Instacart grows a prompt like this in stages, the way the CodeSignal assessment's four levels do, so your stage-one state decides how hard stage three is. Once riders board from a queue as well as by walking up, interviewers keep checking that capacity still holds at every stop. Ties have to break the same way on every run, so you can't iterate a hash set to decide who gets a seat. Keep arrival order in a deque and stage three is mostly the check that keeps the regular line moving.
Take it further
A common stage four is a rider who gives up. Add leave(rider) that pulls a rider out of whichever line they're in, and keep it O(1). Scanning a deque is the obvious approach and the slow one. The version to practice is lazy deletion: mark the rider as gone and skip their entry when it reaches the front of the line.
2

Worker Time and Payroll Tracker: Clock-In Intervals Folded Into a Pay Window

HardSignature problem
Problem
In-store shoppers at Instacart are hourly employees who clock in and out of shifts, and every minute they log has to turn into exact pay. You are building the in-memory ledger behind that. Workers carry a pay rate, attendance arrives as clock-in and clock-out pairs, and payroll asks what a worker earned inside a pay window.

All timestamps are integer minutes and arrive in non-decreasing order across every call. A rate is cents per minute, so every total is an exact integer.

Build PayrollTracker with four methods.

Part 1. Attendance.
- add_worker(worker_id, rate): register a worker paid rate cents per minute. Return True, or False if the id already exists.

- clock_in(worker_id, ts): open a shift at minute ts. Return True, or False if the worker is unknown or already has an open shift. A rejected clock-in leaves the open shift untouched.

- clock_out(worker_id, ts): close the open shift, recording the interval [in, ts). Return True, or False if the worker is unknown or has no open shift.

Part 2. Payroll.
- pay_owed(worker_id, start, end): total cents earned from closed shifts for the minutes inside [start, end). A shift that straddles a window edge counts only its overlapping minutes. A shift still open at query time has no end yet and contributes nothing. An unknown worker owes 0.
  1. PayrollTracker()
  2. add_worker("ana", 20)→ true
  3. clock_in("ana", 100)→ true
  4. clock_out("ana", 160)→ true
  5. pay_owed("ana", 130, 200)→ 600

The shift covers minutes 100 to 160. Only 130 to 160 falls inside the window, 30 minutes at 20 cents each.

How this uses the pattern

A dict from worker id to a small record: the rate, the open clock-in minute if any, and a list of closed [start, end) intervals. Clipping a shift to the pay window is max(start, shift_start) and min(end, shift_end); the overlap is that difference when it is positive.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Worker Time and Payroll Tracker: Clock-In Intervals Folded Into a Pay Window

Loading...
Click "Run" to execute your code
The Instacart angle
Instacart pays two groups of shoppers from timestamps, and this tracker turns a clock-in pair into cents. In-store shoppers work hourly shifts, and full-service shoppers' batch pay includes a time component, so interviewers care more about the arithmetic at the window edge than about the structure holding it. A shift half inside the window, a shift still open at query time, and a second clock-in that must leave the first shift alone are each a hidden test. If stage one stores raw intervals instead of a running total, the rate-change stage becomes one added method.
Take it further
Stage three changes a worker's rate from a given minute onward, including minutes of a shift already in progress. Because clock_out stores the raw interval and not a precomputed total, the rate becomes a per-worker timeline and pay_owed walks it, splitting any shift at the change point. If you compute pay at clock-out instead, the rate change forces a rewrite.
3

Timestamped Task Manager: Logical Clock Over a Map of Tasks

MediumFrequently asked
Problem
An order's fulfillment is a short list of tasks: pick the items, get a substitution approved, check out, hand the bags off. Each task changes status as the shopper works, and every change carries a timestamp from a logical clock the dispatch service owns. You are building the in-memory manager that records those changes and answers what any task's status was at a past moment, plus which tasks were still open then.

Build a class with four methods. Timestamps are non-negative integers. The manager keeps one logical clock: every accepted write (a create or an update) must carry a ts strictly greater than the ts of the previously accepted write, otherwise it is rejected and nothing changes.

Part 1.
- create(task_id, status, ts): start tracking task_id with initial status at time ts. Return True if accepted. Reject with False when task_id already exists or ts does not beat the clock.
- update(task_id, status, ts): record that task_id moved to status at time ts. Return True if accepted. Reject with False when the task is unknown or ts does not beat the clock.

Part 2.
- status_at(task_id, ts): the status in effect at time ts, meaning the most recent accepted write for that task at or before ts. Return the empty string if the task did not exist yet at ts or was never created.
- open_tasks_at(ts): every task that existed at ts and whose status then was anything other than "done", as a list of ids sorted ascending.
  1. TaskManager()
  2. create("t1", "pick", 1)→ true
  3. update("t1", "checkout", 5)→ true
  4. status_at("t1", 4)→ "pick"
  5. status_at("t1", 5)→ "checkout"

At time 4 the only accepted write at or before it is the create at time 1, so the status is still pick. At time 5 the checkout write is in effect.

How this uses the pattern

A dict from task id to its time-ordered history, plus one integer for the clock. Writes compare against the clock and then append, so each history stays sorted on its own. status_at is a rightmost binary search over the task's timestamps, and open_tasks_at runs that read across every task and keeps the ones not done.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Timestamped Task Manager: Logical Clock Over a Map of Tasks

Loading...
Click "Run" to execute your code
The Instacart angle
An Instacart fulfillment order is a task list with a clock on it, and this is one of the most reported problems in the Instacart interviews. Support tools and shopper pay both need to replay what a task looked like at a given moment. Two choices decide the round. Keep a history per task instead of snapshotting every task on each write. Reject a stale timestamp instead of inserting it into the middle of a history that should only grow. Get both right in Part 1 and Part 2 is the same binary search you wrote for the versioned catalog, on a different map.
Take it further
The reported follow-up adds people. Stage 3 assigns tasks to shoppers with assign(task_id, shopper, ts) under the same clock, then asks open_load(shopper, ts): how many still-open tasks that shopper held at time ts. The per-task history handles it, since an assignment is one more timestamped attribute. A shopper-to-tasks index keeps the load query from scanning every task in the system.
4

Banking Operations: A Ledger You Extend a Method at a Time

MediumFrequently asked
Problem
Every Instacart order moves money in several directions at once. The customer is charged, the shopper is paid out, the retailer is settled on its own cycle, and tips and refunds adjust all three after the fact. The service that keeps those balances honest is a ledger.

You are building a small in-memory one in three stages, the way the round itself unfolds. Amounts are whole cents and always positive.

Build Ledger.

Stage 1. Accounts and moves.
- create(account): open an account at a zero balance. Return True, or False if it already exists.

- deposit(account, amount): add to the balance and return the new balance, or -1 if the account does not exist.

- withdraw(account, amount): subtract and return the new balance. Return -1 and leave the balance alone if the account does not exist or cannot cover the amount.

- transfer(src, dst, amount): move money from src to dst and return src's new balance. Return -1 and change nothing if either account is missing, both are the same account, or src cannot cover the amount.

Stage 2. Ranking.
- top(k): return the ids of the k accounts with the highest outgoing volume, where outgoing volume is the total of every successful withdrawal, transfer and scheduled payout sent from that account. Ties break by id ascending. An account that has sent nothing still ranks with a volume of zero, and when fewer than k accounts exist, return all of them.

Stage 3. Scheduled payouts.
- schedule(src, dst, amount, ts): register a payout that comes due at time ts and return its id, "p1" for the first payout ever scheduled, "p2" for the second, and so on. Return "" and schedule nothing if either account is missing or both are the same.

- cancel(payout_id): cancel a payout that has not fired yet. Return True, or False if the id is unknown or the payout has already fired, failed or been cancelled.

- process(ts): fire every pending payout whose due time is at or before ts, in due-time order and, within one due time, in the order they were scheduled. A payout the source cannot cover at the moment it fires fails and is dropped for good. Return the ids of the payouts that fired, in firing order. Only payouts that fired count toward outgoing volume.
  1. Ledger()
  2. create("shopper-ana")→ true
  3. deposit("shopper-ana", 500)→ 500
  4. withdraw("shopper-ana", 200)→ 300
  5. withdraw("shopper-ana", 400)→ -1

The second withdrawal asks for 400 against a balance of 300, so it is rejected and the balance stays at 300.

How this uses the pattern

Two dicts carry the first two stages: balance by account and outgoing volume by account, with the ranking a sort by (-volume, id) sliced to k. Stage 3 adds a min-heap of (due_ts, sequence, payout_id) and a payout table that records each one's status. Cancel flips a status. Process pops the heap while the top is due and skips anything no longer pending.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Banking Operations: A Ledger You Extend a Method at a Time

Loading...
Click "Run" to execute your code
The Instacart angle
Money on an Instacart order settles four ways, and the reported version of this question is a ledger that grows a method at a time. It deposits, withdraws and transfers, then ranks accounts by outgoing volume, then schedules payouts for later, which is shopper earnings and customer wallets in small form. Stage 3 is where candidates get caught. Two payouts due at the same timestamp fire in the order they were scheduled, which matters when the first drains the account and the second has to fail. A cancelled payout never counts toward volume. The hidden tests check both rules.
Take it further
Put a timestamp on every call and let the ledger settle itself. In the version some candidates report, nobody calls process. Every operation carries a ts, and before a deposit, withdrawal, transfer or ranking runs, the ledger fires any payout due at or before that moment. The heap already holds payouts in due order, so the change is a private settle(ts) that each public method calls first, with the same ordering rule. A withdrawal at time 10 must see the payout due at time 10, so settlement runs before the operation, and explaining that order out loud is what interviewers want to hear. That version is worked through below.

Key Takeaways

  • ✓Instacart's staged prompts grow one stage at a time. Choose stage-one state that later stages can extend, like a set plus two deques.
  • ✓Store raw facts and derive totals on read. Payroll stored as [start, end) intervals absorbs a mid-shift rate change by splitting the shift.
  • ✓One logical clock that rejects stale writes keeps task history append-only, so a status-at-time read is a rightmost binary search.
  • ✓Order is part of correctness: riders board in arrival order, and same-timestamp payouts fire in scheduled order via a heap keyed by (due_ts, sequence).
Instacart interview guide

Know what Instacart asks before you walk in.

30 coding · 5 system design · 14 behavioral questions

Get Premium$49 a year · Instant access
Or start freeNo card.

Get their questions first.

Hash Maps & DesignHad your Instacart interview?How we research

InterviewLegend is independent and not affiliated with or endorsed by any company it covers.