Leetcode 1801: Number of Orders in the Backlog

grid47
grid47
Exploring patterns and algorithms
May 10, 2024 9 min read

You are managing an order system for a marketplace where both buy and sell orders are placed in batches. Each order contains a price, a quantity, and a type (either buy or sell). You need to calculate how many orders remain unfulfilled in the system after processing all the orders.
Problem
Approach
Steps
Complexity
Input: The input is a 2D array where each subarray represents an order with three values: price, amount, and order type (0 for buy, 1 for sell).
Example: orders = [[10, 5, 0], [15, 2, 1], [20, 1, 1], [30, 4, 0]]
Constraints:
• 1 <= orders.length <= 100,000
• 1 <= price_i, amount_i <= 10^9
• orderType_i is either 0 (buy) or 1 (sell)
Output: Return the total number of unfulfilled orders in the backlog after processing all the orders, modulo 10^9 + 7.
Example: Output: 6
Constraints:
• The result is modulo 10^9 + 7.
Goal: Process the orders to match buy and sell orders, keeping track of unmatched orders in the backlog.
Steps:
• Initialize two priority queues, one for buy orders and one for sell orders.
• For each order in the input, check if it's a buy or sell order.
• If it's a buy order, try to match it with the cheapest sell order. If no match is found, add it to the buy queue.
• If it's a sell order, try to match it with the most expensive buy order. If no match is found, add it to the sell queue.
• At the end, count the remaining orders in both queues.
Goal: Input size can be large, but operations should be efficient.
Steps:
• Time complexity should be approximately O(n log n), where n is the number of orders.
Assumptions:
• Orders are processed sequentially.
Input: orders = [[10, 5, 0], [15, 2, 1], [20, 1, 1], [30, 4, 0]]
Explanation: In this example, 5 buy orders at price 10 are placed and go into the backlog since no sell orders exist. Then, 2 sell orders at price 15 are added to the backlog, followed by 1 sell order at price 20. Finally, 4 buy orders at price 30 are added, and matching occurs with the 2 lowest-priced sell orders (15 and 20). The remaining orders in the backlog are 5 buy orders with price 10 and 1 buy order with price 30.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus