Number of Orders in the Backlog

Medium Heaps Advanced

Number of Orders in the Backlog is a medium heaps problem solved with the advanced pattern. The best approach, optimal (two heaps), runs in O(n log n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (scan the backlog for the best match) up.

Problem

You are given a list of orders, where orders[i] = [price_i, amount_i, orderType_i] describes a batch of amount_i identical orders, all at price_i. orderType_i is 0 for buy orders and 1 for sell orders.

The orders arrive one batch at a time, in the order of the list. A backlog holds the orders that have not been matched yet; it starts empty. When a batch arrives:

  • A buy batch looks at the cheapest sell order waiting in the backlog. If that sell’s price is at most the buy price, they trade and both orders are removed. This repeats, always against the current cheapest sell, until the batch is used up or the cheapest sell costs more than the buy price. Whatever is left of the batch joins the backlog.
  • A sell batch does the same against the highest-priced buy order in the backlog, trading while that buy’s price is at least the sell price. Whatever is left of the batch joins the backlog.

Each trade matches one buy order with one sell order, so a batch can be partly filled by one waiting batch and partly by the next.

Return the total number of orders left in the backlog after every batch has been processed. The total can be large, so return it modulo 10^9 + 7.

Examples

Example 1

Input
orders = [[8,4,0],[12,3,1],[6,5,1],[10,2,0]]
Output
4
Why
The buy of 4 at 8 finds no sells, so it waits. The sell of 3 at 12 finds no buy paying 12 or more, so it waits too. The sell of 5 at 6 matches the buy at 8 (8 >= 6): 4 are traded and 1 sell at 6 is left over. The buy of 2 at 10 takes that cheapest sell at 6, then stops, because the next sell, at 12, costs more than 10. The backlog ends with 3 sells at 12 and 1 buy at 10: 4 orders.

Example 2

Input
orders = [[5,1000000000,0],[3,7,1],[9,1000000000,1]]
Output
999999986
Why
The sell of 7 at 3 takes 7 from the waiting buy at 5, leaving 999999993 buys. The sell at 9 finds no buy paying 9, so all 10^9 of it waits. The total, 1999999993, is reported modulo 10^9 + 7, which gives 999999986.

Example 3

Input
orders = [[4,2,1],[5,3,1],[6,1,1],[7,5,0]]
Output
1
Why
Three sells wait at 4, 5 and 6. The buy of 5 at 7 sweeps them from the cheapest up: 2 at 4, then 3 at 5, and it is used up exactly. Only the sell of 1 at 6 is left.

Constraints

  • 1 <= orders.length <= 10^5
  • orders[i].length == 3
  • 1 <= price_i, amount_i <= 10^9
  • orderType_i is 0 (buy) or 1 (sell)

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (scan the backlog for the best match)O(n^2)O(n)
Optimal (two heaps)O(n log n)O(n)

1Brute force (scan the backlog for the best match)

TimeO(n^2)Each scan looks at up to n waiting orders. Every scan either empties a waiting order or finishes the incoming one, so there are at most about 2n scans.
SpaceO(n)The two lists hold at most n waiting orders.

Keep the waiting buys and the waiting sells in two plain lists of [price, amount]. When an order arrives, scan the other list for its best partner: for a buy, the cheapest sell whose price is at most the buy price; for a sell, the highest buy whose price is at least the sell price. Trade as much as both can, remove the partner if its amount reaches zero, and scan again until the order is used up or no partner is left. Whatever remains of the order joins its own list.

  1. Keep two lists, buys and sells, each holding [price, amount] pairs.
  2. For each order, pick the other side's list. Scan it for the best matching price; stop if there is none.
  3. Trade take = min(amount, partner amount): subtract it from both, and remove the partner if it hits zero. Repeat while amount > 0.
  4. If amount > 0, append [price, amount] to the order's own list.
  5. At the end, add up every amount in a long and return it modulo 10^9 + 7.
class Solution {
    public int getNumberOfBacklogOrders(int[][] orders) {
        List<long[]> buys = new ArrayList<>(), sells = new ArrayList<>();
        for (int[] o : orders) {
            long price = o[0], amount = o[1];
            boolean isBuy = o[2] == 0;
            List<long[]> other = isBuy ? sells : buys;
            while (amount > 0) {
                int best = -1;
                for (int i = 0; i < other.size(); i++) {
                    long p = other.get(i)[0];
                    boolean fits = isBuy ? p <= price : p >= price;
                    if (fits && (best < 0 || (isBuy ? p < other.get(best)[0] : p > other.get(best)[0]))) best = i;
                }
                if (best < 0) break;
                long[] match = other.get(best);
                long take = Math.min(amount, match[1]);
                amount -= take;
                match[1] -= take;
                if (match[1] == 0) other.remove(best);
            }
            if (amount > 0) (isBuy ? buys : sells).add(new long[] { price, amount });
        }
        long total = 0;
        for (long[] b : buys) total += b[1];
        for (long[] s : sells) total += s[1];
        return (int) (total % 1_000_000_007);
    }
}

2Optimal (two heaps)

TimeO(n log n)Each order is pushed at most once and popped at most once, O(log n) each. Every trade either pops the top or finishes the incoming order, so there are at most 2n trades.
SpaceO(n)The two heaps hold at most n waiting orders between them.

The scan only ever wants one element of the other side: the cheapest sell or the most generous buy. That is exactly what a heap gives. Keep the waiting sells in a min-heap by price and the waiting buys in a max-heap by price. A buy trades with the top sell while that sell's price is at most the buy's price; a sell trades with the top buy while that buy's price is at least the sell's price. Each trade shrinks the top's amount in place, which does not change its price and so keeps the heap valid, and pops the top when it is used up. Whatever is left of the incoming order is pushed onto its own heap.

  1. sells: a min-heap of [price, amount]; buys: a max-heap of [price, amount].
  2. For a buy: while amount > 0 and the top sell's price <= price, trade take = min(amount, top amount); pop the top if it reaches zero. Then push the rest of the buy, if any.
  3. For a sell: the same against the top buy, while its price >= price. Then push the rest of the sell, if any.
  4. Add up every amount left in both heaps in a long and return the sum modulo 10^9 + 7.
class Solution {
    public int getNumberOfBacklogOrders(int[][] orders) {
        PriorityQueue<long[]> buys = new PriorityQueue<>((a, b) -> Long.compare(b[0], a[0]));
        PriorityQueue<long[]> sells = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
        for (int[] o : orders) {
            long price = o[0], amount = o[1];
            if (o[2] == 0) {
                while (amount > 0 && !sells.isEmpty() && sells.peek()[0] <= price) {
                    long[] top = sells.peek();
                    long take = Math.min(amount, top[1]);
                    amount -= take;
                    top[1] -= take;
                    if (top[1] == 0) sells.poll();
                }
                if (amount > 0) buys.offer(new long[] { price, amount });
            } else {
                while (amount > 0 && !buys.isEmpty() && buys.peek()[0] >= price) {
                    long[] top = buys.peek();
                    long take = Math.min(amount, top[1]);
                    amount -= take;
                    top[1] -= take;
                    if (top[1] == 0) buys.poll();
                }
                if (amount > 0) sells.offer(new long[] { price, amount });
            }
        }
        long total = 0;
        for (long[] b : buys) total += b[1];
        for (long[] s : sells) total += s[1];
        return (int) (total % 1_000_000_007);
    }
}

Edge cases to test

  • A single order: nothing to match against, so its whole amount stays in the backlog
  • Only buys or only sells: nothing ever matches and the answer is the sum of all amounts modulo 10^9 + 7
  • Equal prices match: a buy at 5 trades with a sell at 5
  • A large order can sweep several price levels of the other side before it is used up or the prices stop matching
  • Partial fills: the waiting order keeps its price and only its amount goes down; an incoming order that is not fully filled joins the backlog with the rest of its amount
  • A buy never matches a sell that costs more than its price, even if that sell has a huge amount
  • The total can reach 10^5 * 10^9 = 10^14: add amounts in a long and take the modulo at the end

Hints

Hint 1

When a buy arrives, which waiting sell does it trade with first? And when a sell arrives, which waiting buy?

Hint 2

Each side of the backlog only ever needs its best price: the cheapest sell and the most generous buy. Which data structure gives you the smallest or largest element quickly, while orders keep arriving?

Hint 3

Keep sells in a min-heap by price and buys in a max-heap by price. Match against the top while the prices cross, shrink amounts in place, and pop an order once its amount reaches zero.

FAQ

What is the best time complexity for Number of Orders in the Backlog?

Optimal (two heaps) runs in O(n log n) time and O(n) extra space. Each order is pushed at most once and popped at most once, O(log n) each. Every trade either pops the top or finishes the incoming order, so there are at most 2n trades.

Which pattern does Number of Orders in the Backlog use?

It is a heaps problem that uses the advanced pattern. Other problems with the same pattern: Find K Pairs with Smallest Sums, Find Median from Data Stream, Trapping Rain Water II.

Is there a brute force solution for Number of Orders in the Backlog?

Yes. Brute force (scan the backlog for the best match) takes O(n^2) time and O(n) space. Keep the waiting buys and the waiting sells in two plain lists of [price, amount].

Which edge cases should I test for Number of Orders in the Backlog?

A single order: nothing to match against, so its whole amount stays in the backlog; Only buys or only sells: nothing ever matches and the answer is the sum of all amounts modulo 10^9 + 7; Equal prices match: a buy at 5 trades with a sell at 5; A large order can sweep several price levels of the other side before it is used up or the prices stop matching; Partial fills: the waiting order keeps its price and only its amount goes down; an incoming order that is not fully filled joins the backlog with the rest of its amount; A buy never matches a sell that costs more than its price, even if that sell has a huge amount; The total can reach 10^5 10^9 = 10^14: add amounts in a long and take the modulo at the end.