Staged Simulations
- 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
Bus Route Simulation: Boarding, Capacity, Priority in Stages
Problem
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.- BusRoute(1)
- board("A")→ true
- join("B")
- arrive()→ []
- alight("A")→ true
- 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.
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.
Bus Route Simulation: Boarding, Capacity, Priority in Stages
Click "Run" to execute your code
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.Worker Time and Payroll Tracker: Clock-In Intervals Folded Into a Pay Window
Problem
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.- PayrollTracker()
- add_worker("ana", 20)→ true
- clock_in("ana", 100)→ true
- clock_out("ana", 160)→ true
- 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.
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.
Worker Time and Payroll Tracker: Clock-In Intervals Folded Into a Pay Window
Click "Run" to execute your code
Timestamped Task Manager: Logical Clock Over a Map of Tasks
Problem
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.- TaskManager()
- create("t1", "pick", 1)→ true
- update("t1", "checkout", 5)→ true
- status_at("t1", 4)→ "pick"
- 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.
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.
Timestamped Task Manager: Logical Clock Over a Map of Tasks
Click "Run" to execute your code
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.Banking Operations: A Ledger You Extend a Method at a Time
Problem
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.- Ledger()
- create("shopper-ana")→ true
- deposit("shopper-ana", 500)→ 500
- withdraw("shopper-ana", 200)→ 300
- 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.
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.
Banking Operations: A Ledger You Extend a Method at a Time
Click "Run" to execute your code
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 guideKnow what Instacart asks before you walk in.
30 coding · 5 system design · 14 behavioral questions
Get their questions first.
InterviewLegend is independent and not affiliated with or endorsed by any company it covers.