</>

1801. Number of Orders in the Backlog

Medium
Heap / Priority Queue Time O(NlogN) Space O(N)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Heap / Priority Queue
Time
O(NlogN)
Space
O(N)

Standard Solution (C++)

SummarySimulate a live order book: match incoming buy and sell orders greedily against the best available counterpart, consuming quantities until no more compatible pairs exist, then return the total remaining unmatched quantity modulo 10^9+7.

Approach
  • Maintain two heaps: a max-heap for pending buy orders (highest bid on top) and a min-heap for pending sell orders (lowest ask on top).
  • For each incoming buy order, repeatedly match it against the cheapest available sell if that sell price is at most the buy price; for each sell order, match against the highest available buy if that bid is at least the sell price.
  • Partial fills are re-inserted into the appropriate heap with the remaining quantity.
  • After processing all orders, sum every remaining quantity across both heaps under modulo 10^9+7.
#include <vector>
#include <queue>
#include <utility>
using namespace std;

class Solution {
public:
    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
        // max-heap for buy backlog: {price, qty}
        priority_queue<pair<int,int>> buys;
        // min-heap for sell backlog: {price, qty}
        priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> sells;

        for (const auto& o : orders) {
            int price = o[0], qty = o[1], type = o[2];

            if (type == 0) {
                // Buy order: match against cheapest sell while affordable
                while (qty > 0 && !sells.empty() && sells.top().first <= price) {
                    auto [sp, sq] = sells.top(); sells.pop();
                    int matched = min(qty, sq);
                    qty -= matched;
                    if (sq > matched) sells.push({sp, sq - matched});
                }
                if (qty > 0) buys.push({price, qty});
            } else {
                // Sell order: match against highest buy while bid meets ask
                while (qty > 0 && !buys.empty() && buys.top().first >= price) {
                    auto [bp, bq] = buys.top(); buys.pop();
                    int matched = min(qty, bq);
                    qty -= matched;
                    if (bq > matched) buys.push({bp, bq - matched});
                }
                if (qty > 0) sells.push({price, qty});
            }
        }

        const long long MOD = 1e9 + 7;
        long long res = 0;
        while (!buys.empty())  { res = (res + buys.top().second)  % MOD; buys.pop(); }
        while (!sells.empty()) { res = (res + sells.top().second) % MOD; sells.pop(); }
        return static_cast<int>(res);
    }
};
Time O(n log n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
        std::priority_queue<pair<int, int>> max_buy_orders;
        std::priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_sell_orders;

        for(const auto& order: orders){
            int price=order[0];
            int amount=order[1];
            int orderType=order[2];

            if(orderType==0){ // buy
                while(amount>0 && !min_sell_orders.empty()){
                    auto top_cell=min_sell_orders.top();
                    int sell_price=top_cell.first;
                    int sell_amount=top_cell.second;

                    if(sell_price>price){
                        break;
                    }
                    else{ // able to match
                        min_sell_orders.pop();
                        if(sell_amount>amount){
                            min_sell_orders.push({sell_price, sell_amount-amount});
                            amount=0;
                        }
                        else{
                            amount-=sell_amount;
                        }
                    }
                }
                if(amount>0){
                    max_buy_orders.push({price, amount});
                }
            }
            else{ // sell
                while(amount>0 && !max_buy_orders.empty()){
                    auto top_cell=max_buy_orders.top();
                    int buy_price=top_cell.first;
                    int buy_amount=top_cell.second;

                    if(buy_price<price){
                        break;
                    }
                    else{ // able to match
                        max_buy_orders.pop();
                        if(buy_amount>amount){
                            max_buy_orders.push({buy_price, buy_amount-amount});
                            amount=0;
                        }
                        else{
                            amount-=buy_amount;
                        }
                    }
                }
                if(amount>0){
                    min_sell_orders.push({price, amount});
                }
            }
        }

        const long long MOD=1e9+7;
        long long res=0;
        while(!max_buy_orders.empty()){
            res=(res+max_buy_orders.top().second)%MOD;
            max_buy_orders.pop();
        }
        while(!min_sell_orders.empty()){
            res=(res+min_sell_orders.top().second)%MOD;
            min_sell_orders.pop();
        }

        return (int)res;
    }
};

// Time Complexity: O(NlogN)
// Space Complexity: O(N)
Time O(NlogN) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern