Reconcile Unmatched Trades with Timestamp Tolerance
Problem statement
Given a finite batch of trade records, pair compatible buy and sell trades and return the IDs of every trade that remains unmatched.
Each row of trades contains exactly six strings in this order:
tradeId: a unique identifier.symbol: the traded instrument.side: eitherBUYorSELL.priceCents: a positive integer price in cents.quantity: a positive integer quantity.timestamp: a nonnegative integer timestamp.
A buy and a sell are compatible when they have the same symbol, priceCents, and quantity, and the absolute difference between their timestamps is at most tolerance. Each trade may be paired at most once, and partial fills are not used.
Within each shared symbol-price-quantity key, consider buys and sells in ascending timestamp order, breaking equal timestamps by original input position. Pair the earliest remaining buy with the earliest remaining sell whenever they are within the tolerance window. If one is earlier than the other by more than tolerance, that earlier trade is unmatched.
Return all unmatched tradeId values in their original input order.
Function
findUnmatchedTrades(trades: String[][], tolerance: long) → String[]Examples
Example 1
trades = [["b1","AAPL","BUY","10000","5","100"],["s1","AAPL","SELL","10000","5","102"],["b2","MSFT","BUY","25000","2","200"],["s2","MSFT","SELL","25000","2","206"],["b3","AAPL","BUY","10000","7","105"]]tolerance = 2return = ["b2","s2","b3"]b1 and s1 share their symbol, price, and quantity, and their timestamps differ by 2, so they pair. The two MSFT trades differ by 6, and b3 has no sell with quantity 7.
Example 2
trades = [["b1","XYZ","BUY","500","1","10"],["b2","XYZ","BUY","500","1","12"],["s1","XYZ","SELL","500","1","11"],["s2","XYZ","SELL","500","1","20"]]tolerance = 1return = ["b2","s2"]The earliest buy b1 pairs with the earliest sell s1. The remaining timestamps 12 and 20 are outside the tolerance window.
Constraints
1 <= trades.length <= 200000.- Every row contains exactly six values in the documented order.
- Every
tradeIdis unique and everysymbolandtradeIdis non-empty. sideis eitherBUYorSELL.1 <= priceCents, quantity <= 10^9.0 <= timestamp, tolerance <= 10^15.- Numeric row fields are canonical base-10 integer strings without signs or separators.