Order Books & Matching
- Build a price-time priority matcher with two heaps, partial fills and trades at the resting price
- Break ties at one price by arrival, even when order ids come out of order
- Defend a heap against a sorted list or a tree, and say when each wins
- Test a matcher on purpose and explain why your output might differ from the sample
If you have a Two Sigma technical screen coming up, there's a fair chance it's this one. Since late 2024, candidates have described an order matching engine on screens more often than any other problem. A Quantitative Software Engineer met it on HackerRank in July 2026. A software engineer interviewing with a GenAI team got it in spring 2026, and a 2025 SWE phone screen centered on it, solved with min and max heaps.
The core build fits in about fifty lines of Python. What the hour tests is everything around it. How do you break a tie at the same price? What happens when order ids don't arrive in order? Why a heap? How would you test it? The July 2026 candidate wrote that the round was about more than getting the happy path to run.
What the Two Sigma order matching question looks like
The prompt is something like this. You get a stream of limit orders for one stock, each with an id, a side, a price and a quantity. Process them in arrival order. When a new buy is priced at or above the cheapest resting sell, or a new sell at or below the best resting buy, they trade. Print each trade, then print what's left in the book.
Real exchanges run on the same rules and call them price-time priority. The best price trades first. At one price, whoever arrived first trades first. A trade happens at the price of the order already resting in the book, so an aggressive buyer at 105 who hits a sell resting at 101 pays 101. If one side is bigger, the smaller side fills completely and the rest of the bigger order keeps going.
The exact input and output format changes from round to round, so read the one you're given twice. The shape stays the same. Some candidates describe it as a "stock exchange problem" (an intern first round in late 2024). Others call it "trading system order matching" (a 2025 phone screen). In 2026, candidates say "price-time priority" outright.
| When | Role and round | What came after the build |
|---|---|---|
| July 2026 | Quantitative SWE, HackerRank technical screen | Tie-breaks, why a heap, tests, why the output differed from the sample, string building |
| Spring 2026 | SWE on a GenAI team, technical screen | A manager round on past work and GenAI |
| 2025 | Full-time SWE, phone screen | Order numbers that do not arrive in order |
| Late 2024 | SWE intern, first-round video interview | Not described |
Two heaps and a counter are enough. Bids go in a max-heap keyed on price, asks in a min-heap, and each key gets an arrival number as its second field so ties at one price resolve by time. Matching is a loop that peeks at the other side's top, trades the smaller quantity, and pops the resting order only when it's fully filled.
Price-time priority in two heaps
Python's heapq is a min-heap, so the ask side works as is. The bid side stores the negated price, which turns "highest bid first" into "smallest key first". Then add an arrival counter as the second field. Tuples compare left to right, so two orders at the same price come out in the order they arrived.
import heapqbids, asks = [], []arrival = 0# A buy for 5 at 100, then a buy for 3 at 100, then a sell for 4 at 103.arrival += 1; heapq.heappush(bids, [-100, arrival, "order 1"])arrival += 1; heapq.heappush(bids, [-100, arrival, "order 2"])arrival += 1; heapq.heappush(asks, [103, arrival, "order 3"])bids[0] # [-100, 1, "order 1"]: best price, and first in time at that priceasks[0] # [103, 3, "order 3"]: the cheapest sellKeep the remaining quantity outside the heap, in a dict keyed by order id. A partial fill then changes one number and leaves the heap alone. The order keeps its spot at the top, which is what time priority asks for. Popping and pushing it back would also work, but only if you reuse its old arrival number.
Asked at Two Sigma
Here is the core matcher as one runnable class, in the version candidates described from 2024 to 2026. The tests run in the order you'd build it. Resting orders and the book print come first, then full fills, then partial fills across several prices, then ties at one price with ids out of order.
Order Matching Engine With Price-Time Priority
Problem
OrderBook for one stock. submit(order_id, side, price, quantity) takes a limit order, where side is "BUY" or "SELL" and prices are whole ticks. Orders arrive one call at a time. Ids are unique, but they don't have to arrive in increasing order.A new order trades while prices cross. A buy matches asks priced at or below its limit, and a sell matches bids at or above its limit. The best price goes first, and at one price the earliest arrival goes first. Each trade fills the smaller of the two remaining quantities at the resting order's price.
submit returns its trades in order, each as "TRADE buy= sell= price= qty="
. Anything left of the new order rests at its own limit. book() returns the resting orders as "BUY id= price= qty="
lines, best bid first, then "SELL ..." lines, best ask first, in arrival order inside each price.- OrderBook()
- submit(1, "SELL", 101, 3)→ []
- submit(2, "BUY", 101, 5)→ ["TRADE buy=2 sell=1 price=101 qty=3"]
- book()→ ["BUY id=2 price=101 qty=2"]
The buy fills all 3 of the resting sell. Its last 2 have nothing left to match, so they rest as a bid at 101.
Keep bids in a max-heap of [-price, arrival, id] and asks in a min-heap of [price, arrival, id], with remaining quantities in a dict. Match by peeking at the opposite top while prices cross, and pop only a fully filled order.
Order Matching Engine With Price-Time Priority
Click "Run" to execute your code
The follow-ups Two Sigma asks
The July 2026 candidate said the round went well past the happy path. Each question below was asked in a 2025 or 2026 round. Have a short answer ready for each, and say it while you code, before anyone asks.
Ties at the same price
The July 2026 candidate was asked how orders at one price are ordered, and whether the tie-break should be order id, quantity or arrival time. Arrival time is the exchange answer, and it's what price-time priority means. Order id only works when ids are handed out in arrival order, and the 2025 screen showed they may not be.
If the interviewer wants larger orders first at one price, change the second field of the key to the negated original quantity and keep arrival third. Use the original size. A remaining quantity changes with every partial fill, and a heap key that changes after the push breaks the heap.
Why a heap, and would a list or a tree work?
This one came up in July 2026 too, along with whether a heap is optimal. It depends on what else the book has to do.
| Structure | Best order | Add an order | Print the book | When it wins |
|---|---|---|---|---|
| Heap per side | O(1) peek, O(log n) pop | O(log n) | O(n log n) sort | Only adds and matches, as in this problem |
| Sorted list per side | O(1) at the end | O(n), since insort shifts | O(n), already sorted | Small books, or printing after every order |
| Tree of price levels, each a FIFO queue | O(log p) for p prices | O(log p), then O(1) append | O(n) in order | Cancels and modifies, which real engines need |
For submit and match alone, a heap is as good as it gets. Each order is pushed once and popped once. A linked list or plain list forces a linear scan or shift on insert. The tree wins once cancels arrive. Keep a sorted map from price to a queue of orders (TreeMap in Java, std::map in C++) and a dict from id to its order, and a cancel no longer has to dig through a heap.
Testing, and why your output differs from the sample
The July 2026 candidate was asked what tests would raise confidence, and why their output didn't match the sample. A senior candidate back in 2022 was expected to write their own test cases as part of the question. So build a short list before you run the sample. Cover a book with no cross, an exact fill, a partial fill on each side, a sweep across several prices, a tie at one price with ids out of order, and an empty book.
When the output differs from the sample, check the usual suspects in this order. Is the trade price the resting order's? Is the tie-break arrival and not id? Do bids print highest first? Does a partially filled order keep its place? Then check formatting, like spaces, separators and a trailing newline. Saying that list out loud is a good answer even before you find the bug.
String building and what you would change
The July 2026 screen also asked how the output strings were built. In Python, collect lines in a list and join them once at the end. Repeated += on a growing string can copy it each time. In Java use a StringBuilder, and in C++ an ostringstream or reserved string.
The interviewer also asked what you'd change with more time. Good answers are concrete. Add cancel and modify with a tree of price levels and an id index. Validate input, like a zero quantity, an unknown side or a duplicate id. Keep prices in integer ticks or Decimal, never floats. Write a randomized test that checks the book never ends up crossed.
Older trading versions (2021-2024)
Trading-flavored builds have been part of Two Sigma's live coding for years. The older reports are thinner, and they read as the same family rather than the exact 2026 problem.
2024 (February): an intern's final round on HackerRank included "Trading Simulation" next to graph traversal and search.
2022 (May): a senior SWE onsite asked candidates to code a simple simulation of a stock exchange, and coming up with test cases was part of the question.
2022 (January): an SWE onsite asked for an order management system that parses orders and stores the buy and sell sides in order.
2021 (May): an SWE onsite ran three coding rounds back to back, and some involved matching the order of trades.
If you can parse orders, keep both sides sorted and match on a cross, you're covered for every version above. Of these, only the 2022 senior report made your own tests part of the question. The July 2026 screen did the same.
Common questions
What coding question does Two Sigma ask in the phone screen?
Screens usually give you one build-the-thing problem for the hour, with follow-ups. Order matching with price-time priority is the one candidates described most from late 2024 through 2026. Others reported in 2025 and 2026 include a hash map built from scratch, a Premium question and a Huffman-style encoder.
Is the Two Sigma technical screen on HackerRank?
The July 2026 Quantitative SWE screen ran in HackerRank, and a new grad in 2025 was told to expect a live HackerRank too. Two Sigma's own page describes a shared code pair environment and lets you code in C, C++, Java or Python. It also says using ChatGPT or any other AI tool is strictly prohibited.
Is this a LeetCode question?
Not directly. The closest is Number of Orders in the Backlog, which uses the same two heaps but only asks for a count. Two Sigma's version wants the trades, the final book, the tie-break rule and your tests, so practice the full build here.
What comes after the screen?
It depends on the role. The July 2026 Quantitative SWE candidate moved to a resume walk and a deep dive on scaling a quant system with a senior interviewer. The spring 2026 GenAI-team candidate went to a manager round on past work and GenAI. General SWE loops continue to three 60-minute technical interviews.
Key Takeaways
- ✓Order matching with price-time priority is the screen problem candidates described most from late 2024 through 2026.
- ✓Key bids on negated price and asks on price, with an arrival counter second. Never rank ties by order id.
- ✓Trades print at the resting price, and a partly filled order keeps its place until it is empty.
- ✓Write your own tests before the sample, and have answers ready on tie-breaks, heap choice and string building.
Two Sigma interview guideKnow what Two Sigma asks before you walk in.
21 coding · 4 system design · 13 behavioral questions
Get their questions first.
InterviewLegend is independent and not affiliated with or endorsed by any company it covers.