E
edgecase
quant prep

Grind

Interview reps. Try to solve, then tap to reveal.

538 items
0 of 538 mastered538 unseen
Mediumheapdesign

Running Median of a Streaming Mid-Price Feed

You receive a live stream of mid-price ticks for an instrument, one at a time. Design a class exposing add(price), which ingests one more tick, and median(), which returns the median of every tick seen so far.

Input:
add(101.0); add(103.0); add(100.0); add(105.0)
Output:
101.0, 102.0, 101.0, 102.0
After each add the sorted history is [101], [101,103], [100,101,103], [100,101,103,105], with medians 101.0, 102.0 (avg of 101/103), 101.0, and 102.0 (avg of 101/103) respectively.
Tap to reveal solution
Mediumheaphash-table

K Best (Highest) Bid Price Levels from a Stream of Order Book Updates

You receive a stream of order-book updates, each either adding a resting bid of a given price (add(order_id, price)) or fully canceling a previously-added bid by its order id (cancel(order_id)). At any point, query(k) must return the k highest distinct bid price levels currently resting, sorted descending, without rescanning every resting order on each query.

Input:
add(1,101.5); add(2,101.5); add(3,101.0); add(4,102.0); query(2)
Output:
[102.0, 101.5]
Three distinct price levels are resting (102.0, 101.5, 101.0); the two highest are 102.0 and 101.5. Canceling order 4 afterward would remove the 102.0 level entirely since no other order rests there.
Tap to reveal solution
Harddynamic-programming

Best Time to Buy and Sell Stock With At Most Two Transactions

Given daily prices, you may complete at most two non-overlapping buy-then-sell round trips (you must sell before buying again). Return the maximum achievable profit.

Input:
prices=[3,3,5,0,0,3,1,4]
Output:
6
Buy day3 (0), sell day4... actually buy day3 (0), sell day5 (3): profit 3. Buy day6 (1), sell day7 (4): profit 3. Total 3+3=6.
Tap to reveal solution
Mediumsliding-window

Longest Window of Order-Flow Events With At Most K Distinct Tickers

Given a chronological list of ticker symbols events representing an order-flow event stream, and an integer k, return the length of the longest contiguous subarray containing at most k distinct tickers.

Input:
events=["AAPL","AAPL","MSFT","MSFT","GOOG","AAPL"], k=2
Output:
4
The run AAPL, AAPL, MSFT, MSFT (indices 0-3) has exactly 2 distinct tickers and length 4. Extending it to include GOOG at index 4 introduces a third distinct ticker, which breaks the k=2 cap, and no other window reaches length 4 with at most 2 distinct tickers.
Tap to reveal solution
Mediumheapsorting

K Closest Trades to a Reference Price

Given an array of executed trade prices and a reference price, return the k trade prices closest to the reference price, in any order. Distance is measured as absolute difference; on a tie, prefer the smaller price.

Input:
prices=[9.8,10.2,10.0,11.5,9.5], ref=10.0, k=3
Output:
[9.8, 10.0, 10.2]
Distances from 10.0 are 0.2, 0.2, 0, 1.5, 0.5. The three smallest distances belong to 10.0, 9.8, and 10.2.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window With Bounded Drawdown

Given daily prices and a fractional limit, find the length of the longest contiguous window such that within that window the lowest price is never below (1 - limit) times the highest price -- i.e. the peak-to-trough drawdown inside the window never exceeds limit. Return that length.

Input:
prices=[100,103,98,101,90], limit=0.05
Output:
4
The window [100,103,98,101] has max 103 and min 98; 98 is within 5% of 103 (0.95*103=97.85 <= 98). Extending to include 90 breaks the bound, since 90 sits more than 5% below every possible peak in that window.
Tap to reveal solution
Mediumdynamic-programminggreedy

Max Profit With Unlimited Transactions, Allowing Both Long and Short Round-Trips

Given daily prices, you may take unlimited round-trip trades, each either a LONG (buy then sell) or a SHORT (sell-to-open then buy-to-cover), with at most one position open at a time and no overlap between trades. Return the maximum total achievable profit.

Input:
prices=[5,3,8,2,9]
Output:
20
Short the 5->3 drop (+2), go long the 3->8 rise (+5), short the 8->2 drop (+6), go long the 2->9 rise (+7). Total 2+5+6+7=20 -- every single day-to-day move gets captured by picking the matching side.
Tap to reveal solution
Mediumheapdesign

Rolling Median of Order Book Imbalance Ratio (Two Heaps)

You receive a stream of order-book snapshots, each producing an imbalance ratio r = bid_size / (bid_size + ask_size) in [0, 1]. Implement a structure that supports add(r) and median() so you can track the running median imbalance ratio as the session progresses, with add() in O(log n) and median() in O(1).

Input:
add(0.6); add(0.3); add(0.9); add(0.4) -- median() after each add
Output:
0.6, 0.45, 0.6, 0.5
After [0.6]: median 0.6. After [0.3,0.6]: average of the two middles, 0.45. After [0.3,0.6,0.9]: middle value 0.6. After [0.3,0.4,0.6,0.9]: average of the two middles, (0.4+0.6)/2=0.5.
Tap to reveal solution
Harddesignheap

Design an Order Book Supporting Iceberg Orders With Price-Time Priority

Extend a price-time-priority limit order book to support iceberg orders: an iceberg order has a total quantity but only DISPLAYS a fixed slice at a time. When the currently displayed slice is fully filled, the next slice of the same display size automatically replenishes at the same price -- but the replenished slice goes to the BACK of the time-priority queue at that price level, exactly like a real exchange treats iceberg replenishment. Implement add_iceberg_sell(order_id, price, total_qty, display_qty) and add_buy(order_id, price, qty) -> list of (matched_order_id, price, qty) fills.

Input:
add_iceberg_sell(1,100.0,300,100); add_buy(2,100.0,100); add_buy(3,100.0,50)
Output:
[(1,100.0,100)] then [(1,100.0,50)]
The first buy drains the whole 100-share displayed slice. The iceberg still has 200 hidden shares, so it replenishes a new 100-share slice at the same price -- but under a fresh sequence number, so it matches any new resting sell at 100.0 only after that order, not before it.
Tap to reveal solution
Mediumheapdesign

Kth Largest Fill Price From a Stream of Partial Fills

You receive a stream of partial fill reports for a large parent order, each carrying a fill price. Design a class initialized with k and an initial list of fill prices, exposing add(price) that ingests one more price and returns the k-th largest fill price seen so far, in O(log k) time per call.

Input:
k=3, initial=[4,5,8,2]; add(3); add(5); add(10); add(9); add(4)
Output:
4, 5, 5, 8, 8
With k=3 the answer is always the smallest value currently sitting in a size-3 min-heap of the largest prices seen so far.
Tap to reveal solution
Mediumdesignmath

Design a Position Tracker With Average Cost Basis

Design a class tracking a single instrument's position using average-cost accounting. buy(qty, price) increases the position and updates the average cost basis. sell(qty, price) reduces the position, realizes P&L on the sold quantity at (price - avg_cost), and does NOT change avg_cost for the remaining shares. Support realized_pnl(), unrealized_pnl(mark_price), and net_qty(). Selling more than the current position (going short past flat, or covering past flat from a short) must correctly reset or re-establish avg_cost for the new side.

Input:
buy(100,10); buy(100,20); sell(150,25)
Output:
avg_cost after buys = 15.0; realized_pnl after sell = 1500.0; net_qty = 50
Two buys of 100@10 and 100@20 give avg_cost (100*10+100*20)/200=15. Selling 150 at 25 realizes (25-15)*150=1500 profit and leaves 50 shares still at avg_cost 15.
Tap to reveal solution
Mediumsliding-window#209

Smallest Contiguous Window of Trades Whose Total Volume Reaches a Target

Given an array of trade sizes (positive integers, in print order) and an integer target, return the length of the smallest contiguous window of consecutive trades whose sizes sum to at least target, or 0 if no such window exists.

Input:
sizes = [100,50,200,30,40], target = 210
Output:
2
The window [50,200] (indices 1-2) sums to 250 >= 210, and so does [200,30] (indices 2-3) at 230. No single trade reaches 210 on its own, so length 2 is the minimum.
Tap to reveal solution
Harddesignheaphash-map

Design a Price-Time Priority Limit Order Matching Engine

Design a class OrderBook supporting add_order(order_id, side, price, qty), which adds a resting limit order and immediately matches it against the opposite side at or better than its price in strict price-time priority (best price first, earliest-added first among equal prices), partially filling as needed and resting any unfilled remainder; and cancel(order_id), which removes a still-resting order. add_order returns the list of (resting_order_id, fill_qty, fill_price) trades generated.

Input:
add_order(1,'sell',101,50); add_order(2,'buy',102,30)
Output:
trades = [(1, 30, 101)]
Order 2 crosses the book and fills 30 against resting order 1 at order 1's price (101, the resting order's price, the standard convention). Order 1 now rests with 20 remaining; order 2 is fully filled and rests nothing.
Tap to reveal solution
Hardprobabilitymath

Probability a Market-Making Desk's Inventory Is Back to Exactly Flat After N Ticks

A market maker's inventory starts at 0. Each tick it moves +1 with probability p, or -1 with probability (1-p), with no barriers. Given p and a number of ticks n, return the probability that inventory is exactly 0 after n ticks.

Input:
p = 0.6, ticks = 4
Output:
0.3456
Being back at 0 after 4 ticks requires exactly 2 up-moves and 2 down-moves in some order: C(4,2) = 6 such orderings, each with probability 0.6^2 * 0.4^2 = 0.0576, for a total of 6 * 0.0576 = 0.3456.
Tap to reveal solution
Harddesignheap

Design: Limit Order Book With O(log n) Add, Cancel, and Best Bid/Ask

Design an OrderBook supporting add_order(order_id, side, price) to rest a new limit order, cancel_order(order_id) to remove a previously added order, and best_bid() / best_ask() to return the current highest resting buy price / lowest resting sell price (or None if that side is empty). All operations should run in O(log n).

Input:
add_order(1,"BUY",100); add_order(2,"BUY",102); add_order(3,"SELL",105); cancel_order(2); best_bid(); best_ask()
Output:
best_bid() = 100, best_ask() = 105
After order 2 (the best bid at 102) is cancelled, the best remaining bid falls back to order 1 at 100; the best ask is unaffected at 105.
Tap to reveal solution
Hardsliding-window

Shortest Subarray of Signed Trade Quantities Reaching a Target Net Position

Given an array of signed trade quantities (positive for buys, negative for sells) and an integer target, return the length of the shortest contiguous subarray whose sum is at least target. Return -1 if no such subarray exists. Quantities may be any sign, so a plain non-negative sliding window does not directly apply.

Input:
quantities = [3, -1, 5, -2, 7], target = 9
Output:
3
Subarray [5, -2, 7] (indices 2..4) sums to 10, which meets the target 9 over length 3. The only other subarray meeting the target is the full suffix [-1, 5, -2, 7] (indices 1..4), summing to 9 but over length 4, and the whole array sums to 12 over length 5 -- both longer. No length-1 or length-2 subarray reaches 9, so 3 is the shortest.
Tap to reveal solution
Mediumdesign

Design an Incremental Rolling VWAP Tracker

Design a class RollingVWAP(window) that supports add_trade(price, size), recording a new trade, and get_vwap(), returning the volume-weighted average price over only the most recent `window` trades. Both operations must run in O(1) time.

Input:
window = 3; add_trade(100, 10); add_trade(102, 5); add_trade(101, 20); add_trade(105, 5); get_vwap()
Output:
101.8333
After the 4th trade, the (100, 10) trade has rolled out of the window. VWAP over the remaining 3 is (102*5 + 101*20 + 105*5) / (5 + 20 + 5) = 3055 / 30 ~= 101.8333.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With Cooldown

Given daily prices, you may complete as many non-overlapping buy-then-sell round trips as you like, but after selling you must wait one full day (cooldown) before buying again. Return the maximum achievable profit.

Input:
prices=[1, 2, 3, 0, 2]
Output:
3
Buy day0 (1), sell day1 (2): profit 1. Cooldown day2. Buy day3 (0), sell day4 (2): profit 2. Total 1+2=3.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window Where Price Range Stays Within a Band

Given a list of daily closing prices and an integer band, return the length of the longest contiguous window whose price range (max price in the window minus min price in the window) is at most band.

Input:
prices=[8,2,4,7], band=5
Output:
3
The window [2,4,7] (indices 1..3) has range 7-2=5, which is <= band. No length-4 window works: the full array has range 8-2=6 > 5.
Tap to reveal solution
Hardprobabilitymarkov-chain

Probability a Market Maker's Inventory Hits a Risk Limit Before Flattening

A market maker's inventory moves up by one unit with probability p on each fill and down by one unit with probability 1-p, independently each time. Starting at inventory i units away from flat, compute the probability inventory reaches an upper risk limit of N units before it returns to flat (0).

Input:
p = 0.5, i = 2, N = 5
Output:
0.4
For a fair random walk, the classic gambler's ruin result collapses to a simple ratio: probability equals i / N by symmetry, here 2/5 = 0.4.
Tap to reveal solution
Hardsliding-windowmonotonic-deque#239

Sliding Window Maximum

Given an array nums and a window size k, return the maximum value of every contiguous window of size k as the window slides from left to right.

Input:
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output:
[3,3,5,5,6,7]
Tap to reveal solution
Hardprobability

Expected Number of Ticks for a Mean-Reverting Price to Return to Its Starting Level

A price moves up or down by one tick each period with equal probability 1/2 (a symmetric random walk). Given that the price returns to its starting level with probability 1, compute the EXPECTED number of ticks until that first return, and explain the surprising result.

Input:
p = 0.5 (symmetric)
Output:
infinity
A symmetric random walk on the integers returns to its origin with probability exactly 1 (it is recurrent), yet the EXPECTED number of steps to do so is infinite -- an event that is certain to happen can still have an infinite expected waiting time.
Tap to reveal solution
Mediumheapsliding-window

Top K Most Active Tickers in a Sliding Time Window

Given a chronological stream of (ticker, timestamp) trade events and a window size of w consecutive events, return the top k tickers by trade count within the current window, for every window as it slides one event at a time from the start of the stream to the end. Ties break by ticker name ascending.

Input:
events = ["AAPL","MSFT","AAPL","GOOG","AAPL","MSFT","GOOG"], w = 4, k = 2
Output:
[["AAPL","MSFT"], ["AAPL","GOOG"], ["AAPL","GOOG"]]
Windows are events[0:4], events[1:5], events[2:6]: window 1 has AAPL=2, MSFT=1, GOOG=1 -> top 2 is [AAPL, MSFT]. Window 2 drops the first AAPL and adds a second AAPL, giving AAPL=2, GOOG=1, MSFT=1 -> top 2 is [AAPL, GOOG] (GOOG beats MSFT alphabetically on the count-1 tie). Window 3 is similar.
Tap to reveal solution
Mediumsliding-window

Minimum Order-Flow Window Covering Every Required Venue

Given a chronological list of venue codes events representing where each child order routed, and a set required of venue codes that must all appear, return the length of the shortest contiguous subarray that contains every venue in required at least once. Return 0 if no such window exists.

Input:
events=["NYSE","ARCA","NYSE","BATS","ARCA"], required={"NYSE","BATS"}
Output:
4
The window events[0:4] = ["NYSE","ARCA","NYSE","BATS"] is the shortest contiguous run containing both NYSE and BATS at least once; no window of length 3 or less covers both.
Tap to reveal solution
Mediumheapdesign

Price-Time Priority Order Matching Across a Buy/Sell Order Stream

Given a stream of incoming limit orders, each (side, price, qty) in arrival order, match each new order against the resting opposite-side book using price-time priority: a BUY matches the lowest-priced resting SELL at or below its price; a SELL matches the highest-priced resting BUY at or above its price; among equal prices, the earliest-arrived resting order fills first. Any unfilled remainder rests in the book. Return the list of executed trades as (price, qty), in the order they occur, using the resting order's price for each fill.

Input:
orders = [("BUY",100,10), ("SELL",99,4), ("SELL",101,5), ("BUY",101,3)]
Output:
[(100,4),(101,3)]
BUY 100x10 rests (nothing to match against yet). SELL 99x4 crosses the resting BUY@100 (99 <= 100) for a fill of 4 at the resting price 100, leaving BUY 100x6 resting. SELL 101x5 doesn't cross BUY@100 (101 > 100), so it rests. BUY 101x3 crosses the resting SELL@101 for a fill of 3 at 101, leaving SELL 101x2 resting.
Tap to reveal solution
Mediumheap

K Trades Closest to a Reference Price

Given a list of trade prices from today's tape and a reference price ref (e.g. the previous close), return the k trade prices closest to ref, in any order. Closeness is measured by absolute difference; ties broken toward the smaller price.

Input:
prices=[181.2, 185.0, 186.4, 184.9, 190.1], ref=185.0, k=3
Output:
[185.0, 184.9, 186.4]
Distances from 185.0 are 3.8, 0.0, 1.4, 0.1, 5.1 in list order, so the three smallest distances belong to 185.0 (0.0), 184.9 (0.1), and 186.4 (1.4).
Tap to reveal solution
Hardheapdivide-and-conquer

Merge K Sorted Price Streams into One Timeline

You receive k separate feeds of timestamped trade prints, each already sorted by timestamp internally (e.g. one feed per exchange reporting the same symbol). Merge all k feeds into a single globally time-sorted list of prints.

Input:
feeds = [[(1,100.1),(4,100.3)], [(2,100.2),(3,100.25)], [(5,100.4)]]
Output:
[(1,100.1),(2,100.2),(3,100.25),(4,100.3),(5,100.4)]
Each of the 3 feeds is already sorted by timestamp on its own; merging picks the globally smallest timestamp available across all feeds at every step, producing one fully sorted output.
Tap to reveal solution
Easysliding-window

Maximum Average Price Over Any Window of Length K

Given a series of daily closing prices and a fixed window length k, return the maximum average closing price over any k consecutive trading days -- the best k-day smoothing window in the series.

Input:
prices=[10,12,9,15,20,7,8], k=3
Output:
14.67
Window [9,15,20] averages (9+15+20)/3 = 14.67, the best 3-day window in the series -- better than the flatter windows at either end.
Tap to reveal solution
Hardprobabilitymath

Probability of Ruin for a Market Maker's Biased Inventory Walk

A market maker's inventory does a random walk on integer lots 0..N. From any interior state i, inventory moves to i+1 with probability p (a buy fill) or to i-1 with probability q=1-p (a sell fill). The maker is 'ruined' if inventory hits 0 before it ever hits the risk limit N, forcing them to flatten. Given N, a starting inventory i, and p, return the probability of ruin.

Input:
N=4, i=2, p=0.5
Output:
0.5
A symmetric (fair) random walk starting exactly halfway between the two absorbing boundaries has probability of ruin equal to (N-i)/N, which is 2/4=0.5 here.
Tap to reveal solution
Harddynamic-programming

Maximum Profit From At Most Two Round-Trip Trades, Each With a Flat Fee

Given a sequence of daily prices for one instrument and a flat fee charged per completed round-trip trade (buy then sell), return the maximum total profit achievable using at most two non-overlapping round-trip trades (you must sell before buying again).

Input:
prices = [1, 5, 2, 8, 1, 9], fee = 1
Output:
12
Buy at 2 (index 2), sell at 8 (index 3): profit 6-1=5. Buy at 1 (index 4), sell at 9 (index 5): profit 8-1=7. Total 12, which beats any other pair of non-overlapping trades or a single trade across the whole range.
Tap to reveal solution
Mediumsliding-window

Longest Run of Trades Whose Total Notional Stays Within a Capital Limit

Given a sequence of trade notional values (all positive, in execution order) and a capital limit, return the length of the longest contiguous run of trades whose cumulative notional never exceeds the limit.

Input:
notionals = [50, 40, 10, 60, 30], limit = 100
Output:
3
The run [10, 60, 30] sums to exactly 100 and has length 3 -- no longer contiguous run anywhere in the sequence stays at or under the limit.
Tap to reveal solution
Mediumbinary-search

Maximum Tradable AUM Under a Participation Cap

Given each name's average daily dollar volume (ADV) and the fraction of the book's capital a rebalance trades in that name (its turnover fraction), find the maximum AUM such that no single name's dollars-traded exceeds a given participation cap times its ADV.

Input:
adv=[20_000_000, 10_000_000, 50_000_000], turnover_fraction=[0.10, 0.20, 0.05], participation_cap=0.05
Output:
2,500,000
At AUM A, name i trades A*turnover_fraction[i] dollars, capped at participation_cap*adv[i]. The per-name bounds are 10,000,000 / 2,500,000 / 50,000,000 respectively -- name index 1 is the binding constraint at 2,500,000.
Tap to reveal solution
Mediumdesignhash-map

Design a Position Tracker With Weighted-Average Cost Basis and Realized P&L on Partial Sells

Design a class PositionTracker with buy(qty, price), which adds to the position using weighted-average cost accounting, and sell(qty, price), which reduces the position and returns the realized P&L for that sell. Also support get_position(), returning (qty, avg_cost).

Input:
buy(100, 50.0); buy(100, 60.0); sell(50, 70.0); get_position()
Output:
sell returns 750.0; get_position returns (150, 55.0)
Two buys blend to an average cost of 55.0 for 200 shares; selling 50 at 70.0 realizes (70 - 55) * 50 = 750.0 profit, and the remaining 150 shares keep the same 55.0 average cost.
Tap to reveal solution
Mediumheap

Merge K Sorted Trade Feeds Into One Time-Ordered Stream

You're given k separate arrays of trade timestamps (each individually sorted ascending, representing k venues' feeds for the same symbol). Merge them into a single sorted array of all timestamps across all venues.

Input:
feeds = [[1,4,7],[2,3,9],[5,6]]
Output:
[1,2,3,4,5,6,7,9]
Each of the 3 feeds is individually sorted; merging all of them by timestamp interleaves venues as needed, pulling the smallest available timestamp across all feeds at each step until every feed is exhausted.
Tap to reveal solution
Mediumprobabilityrandom-walk

Probability of Hitting a Profit Target Before a Stop-Loss (Gambler's Ruin)

A strategy's running P&L moves up by one unit with probability p and down by one unit with probability 1 - p on each independent trade. Starting from P&L 0, return the probability that the P&L hits +target before it hits -stop (i.e., the strategy locks in its profit target before getting stopped out).

Input:
p = 0.5, target = 3, stop = 2
Output:
0.4
With a fair walk, the classic gambler's-ruin formula collapses to the simple ratio stop / (target + stop) = 2/5 = 0.4 -- the symmetric case has a closed form that doesn't need the general p != 0.5 formula at all.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Round-Trip Trades

Given daily prices and an integer K -- a hard cap on the number of round-trip (buy-then-sell) trades a risk desk allows, imposed independently of unlimited-transaction rules -- find the maximum achievable profit, never holding more than one share at a time.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 (profit 4), then buy at 0, sell at 3 (profit 3). Two transactions, total profit 7, and no plan using at most 2 round trips beats it.
Tap to reveal solution
Mediumdesignqueue

Design a Rolling VWAP Tracker Over the Last K Trades

Design a class that supports add_trade(price, qty), recording a new trade, and vwap(), returning the volume-weighted average price over the most recent k trades (k fixed at construction), both in O(1) time.

Input:
k=3; add_trade(10,100); add_trade(12,50); add_trade(11,150); vwap()
Output:
10.8333...
(10*100 + 12*50 + 11*150) / (100 + 50 + 150) = 3250 / 300 = 10.8333. A 4th add_trade(9,200) would evict the oldest trade (10,100) from the window before the next vwap() call.
Tap to reveal solution
Hardprobabilityexpected-value

Expected Number of Ticks to Observe Every Market Regime At Least Once

A regime classifier labels each tick with one of n equally likely market regimes, independently each tick. Return the expected number of ticks needed to have seen every one of the n regimes at least once.

Input:
n=4
Output:
8.33
This is the coupon collector's problem: expected ticks = n * (1 + 1/2 + 1/3 + 1/4) = 4 * 2.0833 = 8.33.
Tap to reveal solution
Mediumheapstreamingdesign

Kth Largest Order Size in a Live Stream

Design a class KthLargestOrder that is initialized with an integer k and a list of initial order sizes, and supports add(order_size), which inserts a new order size and returns the k-th largest order size seen so far.

Input:
k=3, initial=[4,5,8,2], add(3), add(5), add(10), add(9), add(4)
Output:
4, 5, 5, 8, 8
After adding 3: sorted desc [8,5,4,3,2], 3rd largest is 4. After adding 5: [8,5,5,4,3,2], 3rd is 5. Continues similarly.
Tap to reveal solution
Mediumdesign

Design a Token-Bucket Rate Limiter for Outbound Order Messages

Exchanges cap how many order messages (new orders, cancels, replaces) a session can send per second, throttling or disconnecting sessions that exceed it. Design a class allow(timestamp) that a trading session calls before sending each message, returning True if the message may be sent now (and counts against the budget) or False if it must be held back, given a maximum burst capacity and a steady refill rate per second.

Input:
capacity=5, refill_per_sec=2; calls: allow(0.0) x5, allow(0.1), allow(0.6)
Output:
[True,True,True,True,True, False, True]
All 5 initial tokens are available at t=0, so the first 5 calls succeed and drain the bucket. At t=0.1, only 0.2 tokens have refilled (2/sec * 0.1s), not enough for a 6th call. At t=0.6, another 0.5s has passed since t=0.1, adding 1.0 more token, enough for one more call.
Tap to reveal solution
Hardmarkov-chainlinear-algebra

Expected Days to Default in a Credit-Rating Transition Matrix

Given a Markov transition matrix over credit-rating states where one state (default) is absorbing, compute the expected number of days until absorption starting from each transient (non-default) state, without simulating the chain.

Input:
states=["A","B","D"], Q=[[0.9,0.08],[0.2,0.6]] (transient-to-transient block, D absorbing)
Output:
[20.0, 12.5]
Expected days to default starting from A is 20, from B is 12.5 -- the riskier state B is expected to reach default sooner, computed directly from the fundamental matrix rather than by simulating years of daily transitions.
Tap to reveal solution
Mediumdesign

Design a Per-Client VWAP Aggregator With Daily Reset

Design a class VwapAggregator supporting record_fill(client_id, price, qty, day), which records one execution for a client on a given trading day, and get_vwap(client_id), which returns that client's volume-weighted average price across all fills recorded so far on the CURRENT trading day. The first fill of a new day (for any client) resets every client's accumulated state, since VWAP is a within-day concept.

Input:
record_fill("A", 100.0, 10, day=1); record_fill("A", 102.0, 5, day=1); get_vwap("A"); record_fill("A", 90.0, 10, day=2); get_vwap("A"); get_vwap("B")
Output:
100.6667, 90.0, None
A's day-1 VWAP is (100*10 + 102*5) / 15 = 100.6667. The day=2 fill rolls the trading day forward, wiping every client's accumulated totals, so A's day-2 VWAP is just its one fill, 90.0, and B (no fills yet today) has no VWAP to report.
Tap to reveal solution
Easysliding-window

Longest Window of Consecutive Flat-or-Up Days

Given a daily close-price array, a day i (for i >= 1) is 'non-down' if prices[i] >= prices[i-1]. Day 0 is always non-down by convention. Return the length of the longest contiguous run of non-down days.

Input:
prices = [10, 10, 11, 9, 9, 12, 13, 13, 14]
Output:
4
The run [9, 9, 12, 13] (indices 3-6) has every step non-down, length 4. The run [13, 13, 14] (indices 6-8) extends it further to length 3 only if counted separately -- the true longest window is indices 3-8, length 6, since every consecutive step from 9 onward is non-down.
Tap to reveal solution
Harddynamic-programmingbinary-search

Maximum Profit From a Set of Non-Overlapping Trade Intervals

You're given a list of candidate trades, each as (start, end, profit), where start and end are time indices and the position is held during [start, end). You may execute any subset of trades whose intervals don't overlap. Return the maximum total profit achievable.

Input:
trades = [(1,2,50),(2,4,10),(1,4,40)]
Output:
60
Trade (1,2,50) ends exactly when trade (2,4,10) begins, so they're compatible and together yield 60. The single trade (1,4,40) spans both and yields only 40, which is worse.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Trades Until a Winning Streak of Length K

Each trade independently wins with probability p. Compute the expected number of trades needed to observe the first streak of k consecutive wins.

Input:
p = 0.5, k = 2
Output:
6.0
This is the classic 'expected number of fair coin flips to see two heads in a row' result -- the probability-weighted cost of every failed streak attempt compounds to exactly 6.
Tap to reveal solution
Hardprobabilitymath

Expected Number of Trading Days Until an L-Day Up-Streak

A stock closes up on any given day with independent probability p, and down otherwise. Return the expected number of trading days until you first observe L consecutive up-days in a row.

Input:
p=0.6, L=3
Output:
9.0741
Plugging p=0.6 and L=3 into the closed-form expectation gives (1 - 0.6^3) / (0.4 * 0.6^3) = 0.784 / 0.0864 ~= 9.0741 days.
Tap to reveal solution
Mediumprobability

Gambler's Ruin: Probability a Market Maker's Inventory Hits the Upper Limit First

A market maker's inventory starts at i shares (integer) and moves by +1 on each incoming buy fill (probability p) or -1 on each incoming sell fill (probability 1 - p), one fill at a time, independently. The desk has a hard inventory band [0, N]: inventory is forced flat and the walk stops the moment it hits either 0 or N. Given i, N, and p, compute the probability the walk hits N (the upper limit) before it hits 0.

Input:
i = 3, N = 10, p = 0.5
Output:
0.3
With p = 0.5 (a fair, symmetric walk), the classic gambler's ruin formula reduces to the simple linear case: probability of hitting N first equals i / N = 3 / 10 = 0.3, regardless of the step-size details, because a symmetric random walk's hitting probability is exactly proportional to starting position.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With a Transaction Fee

Given daily prices and a fixed fee charged once per completed round trip, you may complete as many transactions as you like (hold at most one share at a time, sell before buying again). Return the maximum achievable profit.

Input:
prices=[1, 3, 2, 8, 4, 9], fee=2
Output:
8
Buy at 1, sell at 8: profit 8-1-2=5. Buy at 4, sell at 9: profit 9-4-2=3. Total profit 5+3=8.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Ticks Until an Inventory Random Walk Hits Either Limit

A market maker's inventory starts at s shares, with 0 < s < N, and each tick moves to s + 1 with probability p or s - 1 with probability 1 - p, until it is absorbed at either 0 or N. Given p, N, and s, return the EXPECTED NUMBER OF TICKS until absorption (not which barrier it hits).

Input:
p = 0.5, N = 4, s = 2
Output:
4.0
For an unbiased (p = 0.5) walk, the expected duration has the closed form s * (N - s): 2 * (4 - 2) = 4.0.
Input:
p = 0.6, N = 3, s = 1
Output:
2.105
With a favorable upward drift (p = 0.6), the biased closed-form expression gives roughly 2.105 ticks on average before the walk hits either 0 or 3.
Tap to reveal solution
Mediumdesignheap

Design a Limit Order Book With O(log n) Best Bid/Ask and Cancel

Design a class supporting add_order(order_id, side, price, quantity) where side is 'buy' or 'sell', cancel_order(order_id), best_bid() returning the highest active buy price (or None), and best_ask() returning the lowest active sell price (or None).

Input:
add_order(1,'buy',100.5,10); add_order(2,'buy',101.0,5); add_order(3,'sell',102.0,8); best_bid(); cancel_order(2); best_bid()
Output:
101.0, then 100.5
Before the cancel, order 2's price 101.0 is the highest active bid; after cancelling it, order 1's 100.5 becomes the best remaining bid.
Tap to reveal solution
Mediumdesignsliding-window

Design: Per-Client Order-Rate Limiter for a Trading Gateway

Design an OrderGateway that enforces, per client_id, a maximum of max_orders submissions within any rolling window_ms-millisecond window. allow(client_id, timestamp_ms) returns True and records the submission if it's within the limit, or False (and does not record it) if the client has already hit the cap within the trailing window.

Input:
max_orders=3, window_ms=1000; allow(c1,0); allow(c1,200); allow(c1,500); allow(c1,900); allow(c1,1100)
Output:
True, True, True, False, True
At t=900, client c1 already has 3 submissions (0, 200, 500) within the trailing 1000ms window, so a 4th is rejected. By t=1100, the submission at t=0 has fallen outside the trailing window (1100-1000=100 > 0), so only 2 remain inside it (200, 500, 900) and the new one is allowed.
Tap to reveal solution
Mediumheap

K Trade Prices Closest to the Current Mid Price

Given a list of trade prices trades and a mid price mid, return the k trade prices closest to mid, ordered by increasing distance from mid (ties broken by the smaller price first). Do this without fully sorting the entire list by distance.

Input:
trades=[101.0, 98.5, 100.2, 103.0, 99.8], mid=100.0, k=3
Output:
[99.8, 100.2, 101.0]
Distances from mid are 100.2->0.2, 99.8->0.2, 101.0->1.0, 98.5->1.5, 103.0->3.0. The three smallest distances are 0.2 (99.8), 0.2 (100.2), and 1.0 (101.0); the 0.2 tie breaks toward the smaller price, so 99.8 sorts before 100.2.
Tap to reveal solution
Mediumdynamic-programming#714

Maximum Profit With a Per-Trade Commission Fee

Given daily prices and a fixed commission fee charged on every completed sell, you may buy and sell as many times as you like, never holding more than one share at once. Return the maximum achievable profit after fees.

Input:
prices = [1, 3, 2, 8, 4, 9], fee = 2
Output:
8
Buy at 1, sell at 8 (profit 7 - 2 fee = 5), buy at 4, sell at 9 (profit 5 - 2 fee = 3). Total 5 + 3 = 8, which beats taking more, smaller round trips once the fee is netted out of each one.
Tap to reveal solution
Mediumdesignreservoir-samplingrandomization

Reservoir Sampling a Fixed-Size Random Snapshot from an Unbounded Trade Stream

You receive an unbounded stream of trade prints one at a time (you don't know the total count in advance and can't store them all). Design a structure that, at any point, can return a uniformly random sample of exactly k trades seen so far (each trade equally likely to be among the k currently held, regardless of when the stream stops).

Input:
k = 2; stream: t1, t2, t3, t4, t5
Output:
after all 5, sample() returns 2 trades, each of the 5 having been included with probability 2/5
Reservoir sampling guarantees every trade seen so far has equal probability k/n of being in the current sample, without ever storing more than k trades or knowing n in advance.
Tap to reveal solution
Easyhash-maptwo-pointer

Two Fills Summing to a Target Notional

Given an array of fill sizes (in shares) for a single order and a target total share count, return the indices of the two fills whose sizes sum exactly to the target, or an empty list if no such pair exists.

Input:
fills=[300, 150, 500, 250], target=400
Output:
[1, 3]
fills[1] + fills[3] = 150 + 250 = 400.
Tap to reveal solution
Hardprefix-sumhash-mapsliding-window

Shortest Contiguous Window of Fills That Flattens a Running Position to Zero

Given an array of signed share deltas from a sequence of fills (positive = buy, negative = sell), find the length of the shortest contiguous window whose deltas sum to exactly zero (the position taken on during that window is fully flat by its end). Return -1 if no such window exists.

Input:
deltas = [100, -50, -50, 30, -30]
Output:
2
deltas[0:3] = [100, -50, -50] sums to 0 (length 3), but deltas[3:5] = [30, -30] also sums to 0 and is shorter, at length 2.
Tap to reveal solution
Harddynamic-programmingbinary-searchgreedy

Maximum Profit Selecting Non-Overlapping Trade Opportunities

You're given a list of trade opportunities, each with a start time, an end time (you hold the position for that whole window and cannot open another that overlaps it), and a profit. Choose a subset of non-overlapping opportunities that maximizes total profit. Two opportunities are non-overlapping if one ends at or before the other starts.

Input:
opportunities=[(1,3,50),(2,5,20),(4,6,70),(6,8,30)]
Output:
150
(4,6) ends at 6 and (6,8) starts at 6, so they're compatible: taking (1,3,50), then (4,6,70), then (6,8,30) totals 50+70+30=150, which beats every other combination -- picking greedily by highest profit first (start with (4,6,70)) can miss compatible follow-on opportunities like this, which is exactly why this needs DP, not a greedy profit-sort.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Expected Days Until a Margin Account Hits Liquidation

A margin account's health state moves each day among states 0..n (0 = liquidated, an absorbing state; n = fully healthy) according to a given one-day transition matrix. Starting from a given healthy state, return the expected number of days until the account first reaches state 0.

Input:
P (3 states: 0=liquidated, 1=warning, 2=healthy) = [[1,0,0],[0.3,0.5,0.2],[0.05,0.25,0.7]], start=2
Output:
7.5
Solving (I - Q) e = 1 over the two transient states (warning, healthy) gives expected absorption times of 5 days from warning and 7.5 days from healthy -- healthy takes longer in expectation to REACH liquidation, which is the expected direction, even though it also has its own small 0.05 direct-to-liquidation chance each day.
Tap to reveal solution
Harddesign

Design a Limit Order Book (Top-of-Book Matching Engine)

Design a class LimitOrderBook supporting add_order(order_id, side, price, quantity) where side is 'buy' or 'sell', cancel_order(order_id), and best_bid_ask() returning a (best_bid_price, best_ask_price) tuple (None for a side with no resting orders). An incoming order that crosses the opposite side's best price should execute immediately, in price-time priority, against resting orders before any unfilled remainder rests on the book.

Input:
add_order(1,'buy',100,10); add_order(2,'sell',101,5); best_bid_ask(); add_order(3,'sell',100,10); best_bid_ask()
Output:
(100, 101), then (None, 101)
Order 3 crosses the resting bid at 100 and fully fills against it (10 for 10), so order 1 is gone and the bid side is empty, while order 2's resting ask at 101 is untouched.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Minimum Window Reaching a Target Notional

Given an array of per-minute traded notional (price times volume, always non-negative) and a target notional, return the length of the SHORTEST contiguous window of minutes whose summed notional is at least the target. Return 0 if no window reaches the target even using the entire array.

Input:
notional=[100, 50, 200, 30, 40], target=280
Output:
3
The window [50, 200, 30] (indices 1-3) sums to 280, meeting the target in 3 minutes -- no shorter window reaches 280.
Tap to reveal solution
Mediumprobabilitymath

Stationary Distribution of a Market Regime Markov Chain

A simplified market-regime model has three states: Bull, Chop, Bear, with a given daily transition probability matrix P (P[i][j] is the probability of moving from state i to state j tomorrow). Given P, compute the stationary distribution: the long-run fraction of days spent in each regime, assuming the chain is irreducible and aperiodic.

Input:
P=[[0.90,0.08,0.02],[0.20,0.60,0.20],[0.05,0.25,0.70]] (rows/cols ordered Bull, Chop, Bear)
Output:
[0.619, 0.195, 0.186] (approximately)
Solving pi*P=pi with pi summing to 1 gives the long-run regime frequencies. Bull dominates here because it has the highest self-transition probability (0.90, the 'stickiest' state).
Tap to reveal solution
Mediumdesign

Design a Position Tracker With Running Average Cost Basis and Realized/Unrealized P&L

Design a class PositionTracker supporting trade(qty, price) -- a positive qty buys, a negative qty sells, and qty may flip the position from long to short or vice versa in one call -- and pnl(mark_price), which returns (realized_pnl, unrealized_pnl) using a running volume-weighted average cost basis for the currently open position.

Input:
trade(100, 10.0); trade(-40, 12.0); pnl(mark_price=11.0)
Output:
(80.0, 60.0)
Buying 100 at 10.0 sets cost basis to 10.0. Selling 40 at 12.0 realizes (12.0 - 10.0) * 40 = 80.0 and leaves 60 shares still at cost basis 10.0. Marking the remaining 60 shares at 11.0 gives unrealized P&L of (11.0 - 10.0) * 60 = 60.0.
Tap to reveal solution
Mediumheapgreedy#621

Order Submission Cooldown Scheduler (Self-Trade Prevention Rate Limiter)

A desk must submit a backlog of pending orders, one per time slot, drawn from several symbols. To satisfy a self-trade-prevention rule, two orders for the SAME symbol must be separated by at least `cooldown` time slots (idle slots are allowed while waiting). Given the count of pending orders per symbol and the cooldown, return the minimum number of time slots needed to submit every order.

Input:
counts = [3, 3], cooldown = 2
Output:
8
Two symbols with 3 orders each, needing a 2-slot gap between same-symbol submissions: A B idle A B idle A B is one valid 8-slot schedule, and nothing shorter satisfies the cooldown for both symbols.
Tap to reveal solution
Mediumdynamic-programming

Minimum Trades to Reach a Target Position Size (Coin Change variant)

A venue only accepts child orders in a fixed set of clip sizes (e.g. 100, 500, 1000 shares -- you can send as many orders of each size as you want, in any combination). Given the available clip sizes and a target position size, return the minimum number of orders needed to reach EXACTLY the target size, or -1 if it's impossible.

Input:
clip_sizes = [1, 100, 500], target = 1200
Output:
4
Two orders of 500 plus two orders of 100 reach exactly 1200 in 4 orders, which is fewer than any combination using only the size-1 clip or other mixes.
Tap to reveal solution
Harddesignqueue

Design a FIFO Position Tracker With Realized/Unrealized PnL

Design a class PositionTracker with buy(qty, price) to add shares to a long position, sell(qty, price) to reduce it using FIFO lot matching (the oldest unsold shares are closed first), and unrealized_pnl(mark_price) / realized_pnl() to report PnL. Assume the position never goes short (sell quantity never exceeds current holdings).

Input:
buy(100,10.0); buy(50,12.0); sell(120,15.0); realized_pnl(); unrealized_pnl(16.0)
Output:
realized_pnl=560.0, unrealized_pnl=120.0
FIFO closes the oldest lot first: all 100 shares bought at 10.0 close for a profit of (15-10)*100=500, then the sell still needs 20 more shares, closing 20 of the 50 shares bought at 12.0 for (15-12)*20=60. Total realized is 500+60=560. The remaining 30 shares from the 12.0 lot are still open, marked at 16.0 for an unrealized profit of (16-12)*30=120.
Tap to reveal solution
Mediumheap

Top-K Largest Single-Day Losses From a Streaming PnL Series

Given a stream of daily PnL values arriving one at a time via add_pnl(value), maintain and return the K largest LOSSES seen so far (the K most negative values, reported as positive magnitudes in descending order) at any point via get_top_losses(), without re-sorting the entire history on every call.

Input:
add_pnl(-5); add_pnl(3); add_pnl(-12); add_pnl(-1); get_top_losses() with k=2
Output:
[12, 5]
The two largest-magnitude losses seen so far are -12 and -5, reported as positive magnitudes in descending order. The gain of 3 and the small loss of 1 never enter the top-2.
Tap to reveal solution
Harddesign

Design a Price-Time Priority Limit Order Matching Engine

Design a class MatchingEngine that processes submit(side, price, size) for a single instrument, where side is 'buy' or 'sell'. An incoming order matches against resting orders on the OPPOSITE side at the best available price (highest bid for an incoming sell, lowest ask for an incoming buy), with ties broken by time priority (earlier orders fill first). Any unmatched remainder rests in the book. Return the list of fills (price, size) produced by this order, in the order they occurred.

Input:
submit("buy", 101, 10); submit("sell", 100, 4); submit("sell", 100, 10)
Output:
[], [(101, 4)], [(101, 6)]
The resting buy order at 101 for 10 shares sits in the book first. The first sell at 100 for 4 crosses it (100 <= 101) and fills 4 shares at the resting order's price of 101, leaving 6 resting. The second sell at 100 for 10 fills the remaining 6 shares of that same resting order at 101, then has 4 shares left with no more resting buys to match, so those 4 rest as a new sell order in the book.
Tap to reveal solution
Mediumprobability

Majority-Vote Accuracy of N Independent Trading Signals (Condorcet Jury Theorem)

You have n independent trading signals (n odd), each correct about tomorrow's direction with the same probability p > 0.5. You combine them by majority vote. Return the probability that the majority vote is correct.

Input:
n = 5, p = 0.6
Output:
0.6826
P(majority correct) = P(at least 3 of 5 correct) under Binomial(5, 0.6), which works out to about 68.3% -- noticeably higher than any single signal's own 60% accuracy.
Tap to reveal solution
Hardprobability

Expected Number of Trades Until Two Consecutive Winning Trades

Each trade independently wins with probability p. Return the expected number of trades needed until you observe two wins in a row for the first time.

Input:
p = 0.5
Output:
6.0
The classic 'expected flips until two heads in a row' result for a fair coin is 6.
Tap to reveal solution
Mediumdynamic-programmingbinary-search

Longest Increasing Subsequence of Daily Signal Scores

Given a daily momentum-ranking score for one name over n days, find the length of the longest subsequence of days (not necessarily contiguous) on which the score is strictly increasing -- a proxy for the longest a trending regime persisted underneath the day-to-day noise.

Input:
scores=[3,1,4,1,5,9,2,6]
Output:
4
One longest strictly increasing subsequence is [1,4,5,9] (days 1,2,4,5), and no strictly increasing subsequence of length 5 exists in this array, so the answer is 4.
Tap to reveal solution
Harddesignheap

Design a Top-of-Book Tracker Supporting O(log n) Add and Cancel

Design a class TopOfBook supporting add_bid(order_id, price), add_ask(order_id, price), cancel(order_id) (the id may belong to a resting bid or ask), best_bid(), and best_ask(). best_bid()/best_ask() return the price of the highest live bid / lowest live ask among orders not yet cancelled, or None if there are none.

Input:
book=TopOfBook(); book.add_bid(1,100.0); book.add_bid(2,100.5); book.add_ask(3,101.0); book.cancel(2); book.best_bid()
Output:
100.0
Order 2 was the best bid at 100.5, but it gets cancelled before best_bid() is called, so the best LIVE bid is order 1 at 100.0 -- the cancelled order must never surface as the top even though it's still technically sitting in whatever internal structure holds it.
Tap to reveal solution
Hardheaptwo-heapsdesign#295

Find Median from Data Stream

Design a class that supports addNum(int) and findMedian() over the running stream of inserted values.

Input:
add 1, add 2, find -> ?, add 3, find -> ?
Output:
1.5, 2
Tap to reveal solution
Harddynamic-programming

Max Profit With Unlimited Trades, a Flat Fee Per Trade, and a One-Day Cooldown After Selling

Given a daily price array and an integer fee charged on every sell, you may buy and sell an unlimited number of times, but after selling you must wait one full day (a cooldown) before buying again. Return the maximum achievable profit.

Input:
prices = [1,2,4], fee = 1
Output:
2
Buy at 1, sell at 4: profit = (4 - 1) - 1 = 2. Buying at 1 and selling at 2 then trying to re-enter is blocked by the cooldown day and nets a worse result anyway.
Tap to reveal solution
Mediumheap

Kth Largest Trade Size Seen So Far (Streaming)

Design a class that ingests trade sizes one at a time as they print, and after each ingestion reports the k-th largest trade size among all trades seen so far, or None if fewer than k trades have printed yet.

Input:
k=3; add(5); add(8); add(2); add(10); add(4)
Output:
None, None, 2, 5, 5
Fewer than 3 trades after the first two adds, so None. After [5,8,2] sorted descending is [8,5,2], 3rd largest is 2. After [5,8,2,10] sorted descending is [10,8,5,2], 3rd largest is 5. After [5,8,2,10,4] sorted descending is [10,8,5,4,2], 3rd largest is still 5.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Days Until K Consecutive Up-Days

Each trading day is independently an up-day with probability p and a down-day with probability 1-p. Return the expected number of days until you first observe a run of K consecutive up-days in a row.

Input:
p=0.5, k=2
Output:
6.0
For a fair coin needing 2 consecutive successes, the closed-form expected waiting time (1 - p^k) / ((1-p) * p^k) evaluates to (1-0.25) / (0.5*0.25) = 0.75/0.125 = 6.0 days.
Tap to reveal solution
Hardheap

Running Median of Streaming Daily P&L

Given a stream of daily P&L values arriving one at a time, maintain and return the running median after each new value arrives, without re-sorting the whole history on every insertion.

Input:
pnl=[5, -2, 8, -10, 3]
Output:
[5.0, 1.5, 5.0, 1.5, 3.0]
After [5,-2] sorted is [-2,5], median 1.5. After [5,-2,8] sorted is [-2,5,8], median 5. And so on -- each median uses only the values seen so far.
Tap to reveal solution
Mediumarraydynamic-programmingkadane#53

Maximum Subarray (Kadane's)

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Input:
nums = [-2,1,-3,4,-1,2,1,-5,4]
Output:
6
[4,-1,2,1] sums to 6.
Input:
nums = [1]
Output:
1
Tap to reveal solution
Mediumsliding-windowhash-map

Smallest Window of Prints Containing All Required Venues

Given a time-ordered list venues of venue names for consecutive trade prints, and a set required of venue names, return the length of the shortest contiguous window of prints that contains at least one print from every venue in required. Return 0 if no such window exists.

Input:
venues=["NYSE","ARCA","NYSE","BATS","ARCA","NYSE"], required={"NYSE","ARCA","BATS"}
Output:
3
The window at indices 1..3 ("ARCA","NYSE","BATS") has length 3 and contains all three required venues. No shorter window does.
Tap to reveal solution
Mediumsliding-window

Longest Trading Window With At Most K Illiquid Minutes

Given an array of per-minute traded volumes (a minute with zero volume is 'illiquid') and an integer k, return the length of the longest contiguous window containing at most k illiquid minutes.

Input:
volume=[5, 0, 3, 0, 0, 8, 2], k=1
Output:
3
Windows [5, 0, 3] and [0, 8, 2] each contain exactly one illiquid minute and have length 3. Every length-4 window (e.g. [5,0,3,0] or [0,0,8,2]) contains at least two illiquid minutes, so 3 is the longest valid window.
Tap to reveal solution
Mediumheap

Merge K Chronological Trade-Print Streams Into One Ordered Stream

Given k separate streams of trade prints (each already sorted by timestamp) reporting the same symbol from k different venues, each stream a list of (timestamp, price) tuples, merge all k streams into a single list sorted by timestamp.

Input:
streams = [[(1,10),(5,11)], [(2,10.5),(3,10.8)], [(4,10.9)]]
Output:
[(1,10),(2,10.5),(3,10.8),(4,10.9),(5,11)]
Each input stream is individually sorted by timestamp; the merged output interleaves all three streams into one globally timestamp-sorted sequence.
Tap to reveal solution
Mediumheapdesign

Running Median of Trade Prices via Two Heaps

Design a class that ingests trade prices one at a time via add(price) and returns the running median of all prices seen so far via median(). The median must be available after every add call in better than O(n log n) time overall.

Input:
add(30); add(10); median() -> 20.0; add(20); median() -> 20.0
Output:
running median after each query
After [30,10], sorted is [10,30], median is their average 20.0. After adding 20, sorted [10,20,30], median is the middle value 20.0.
Tap to reveal solution
Hardprobabilitymath

Probability of Hitting a Profit Target Before a Stop-Loss (Gambler's Ruin)

A trader's PnL moves up by one unit with probability p and down by one unit with probability 1-p on each trade, starting at 0. Given a profit target T (a positive integer) and a stop-loss S (a positive integer, so the trader stops at -S), return the probability the trader hits the profit target before the stop-loss.

Input:
p=0.5, T=3, S=2
Output:
0.4
With a fair coin (p=0.5), the probability of reaching +3 before -2 from a symmetric random walk is simply S / (S + T) = 2/5 = 0.4 -- the classic gambler's ruin result for the fair case.
Tap to reveal solution
Mediumprobabilitymath

Probability of Ruin for a Biased Random Walk Position

A trader's inventory starts at i lots (0 < i < N). Each tick it moves +1 with probability p and -1 with probability 1-p, independent across ticks, until it hits 0 (ruin) or N (target). Return the probability the position hits 0 before N.

Input:
i=4, N=10, p=0.5
Output:
0.6
At p=0.5 (fair walk), ruin probability is linear in the starting point: (N-i)/N = (10-4)/10 = 0.6.
Input:
i=4, N=10, p=0.6
Output:
approximately 0.1834
With a favorable upward drift (p=0.6), ruin probability follows the biased gambler's-ruin closed form and drops well below the fair-walk value, since the walk is now more likely to drift toward N than toward 0.
Tap to reveal solution
Mediumheapmerge-k-sorted

Merge K Live Bid Streams Into One Best-Bid Sequence

You are given k venues, each streaming its own resting bid prices for the same instrument as a list already sorted in decreasing order (best bid first, matching how each venue reports its own book). Merge all k lists into one globally sorted (decreasing) sequence of bid prices representing the combined view across every venue -- the sequence a smart order router walks when hunting for the best available price.

Input:
bids = [[102.5,101.0,100.0],[103.0,100.5],[101.5,101.0,99.5]]
Output:
[103.0,102.5,101.5,101.0,101.0,100.5,100.0,99.5]
A standard k-way merge of already-sorted (descending) lists, preserving duplicate price levels that happen to appear at more than one venue.
Tap to reveal solution
Easyheap

K Best Sharpe Ratios From a Streaming Backtest Grid Search

A grid search streams in (param_id, sharpe) pairs one at a time from parallel backtest workers -- you don't know the total count in advance and can't hold them all in memory. Maintain the k best (param_id, sharpe) pairs seen so far and support returning them, sorted by Sharpe descending, at any point.

Input:
k=2, stream=[(1,0.8),(2,1.9),(3,1.2),(4,2.1),(5,0.5)]
Output:
[(4,2.1),(2,1.9)]
After streaming all five results, the two highest Sharpes seen are param 4 (2.1) and param 2 (1.9); the rest never displaced them from the size-2 heap.
Tap to reveal solution
Mediumdesign

Design a Token Bucket Rate Limiter for Outbound Orders

Design a class OrderRateLimiter that enforces an exchange's throttle: at most capacity orders may be sent in any rolling window, refilling at refill_rate tokens per second, via try_send(timestamp) which returns True (consume a token, order allowed) or False (reject, would exceed the exchange's rate limit) given the current timestamp in seconds.

Input:
capacity=3, refill_rate=1.0; try_send(0.0) x3, then try_send(0.5), then try_send(1.2)
Output:
True, True, True, False, True
Starting with a full bucket of 3 tokens, three immediate sends at t=0 drain it to empty. A send at t=0.5 has only refilled 0.5 tokens, not enough for a full token, so it's rejected. By t=1.2, enough additional time has passed to refill at least one token, so that send succeeds.
Tap to reveal solution
Mediumprobability

Long-Run Fraction of Time in Each Market Regime (Markov Stationary Distribution)

A simple regime model has three states -- trending, mean-reverting, choppy -- with a given daily transition probability matrix (row i, column j = probability of moving from state i to state j tomorrow). Assuming the chain runs for a very long time, return the long-run (stationary) fraction of days spent in each regime.

Input:
P = [[0.80, 0.15, 0.05], [0.20, 0.70, 0.10], [0.30, 0.30, 0.40]] # rows: trending, mean-reverting, choppy
Output:
[0.5263, 0.3684, 0.1053]
The stationary vector pi satisfies pi @ P = pi with sum(pi) = 1. Solving that linear system gives roughly 52.6% of days trending, 36.8% mean-reverting, and 10.5% choppy in the long run.
Tap to reveal solution
Mediumsliding-windowtwo-pointers

Longest Trade Window Under a Notional Risk Cap

Given a chronological list of trade notionals (all positive) and a risk cap, find the length of the longest contiguous window of trades whose total notional does not exceed the cap.

Input:
notionals=[50,20,40,10,30], cap=70
Output:
3
The window [20,40,10] (indices 1-3) sums to 70 and has length 3, the longest window found; every longer window either exceeds the cap or isn't achievable, e.g. [50,20,40] sums to 110.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Rolling High-Water-Mark Alert over a Sliding Tick Window

Given a sequence of price ticks and a window size w, compute, for every window of w consecutive ticks, the maximum price in that window -- a rolling high-water mark used to trigger a trailing-stop alert -- in a single pass rather than rescanning each window from scratch.

Input:
ticks=[3,1,4,1,5,9,2,6], w=3
Output:
[4,4,5,9,9,9]
The window [3,1,4] has max 4, [1,4,1] has max 4, [4,1,5] has max 5, and so on through the final window [9,2,6] with max 9 -- six windows total for 8 ticks and w=3.
Tap to reveal solution
Hardprobabilitydynamic-programmingmarkov-chain

Gambler's Ruin: Probability of Reaching a Profit Target Before a Stop-Out

A trader starts with i units of capital (integer). On each round, capital increases by 1 unit with probability p and decreases by 1 unit with probability 1-p. Trading stops if capital hits 0 (ruin) or hits N (profit target, N given). Return the probability of reaching N before hitting 0, given starting capital i, target N, and win probability p.

Input:
i=2, N=4, p=0.5
Output:
0.5
With a fair coin (p=0.5), the classic gambler's ruin result gives probability i/N = 2/4 = 0.5, since the fair-odds case reduces to a simple linear ratio.
Tap to reveal solution
Mediumsliding-window

Longest Window Tolerating at Most K Rejected Orders

Given a sequence of order outcomes, where 1 marks a rejected order and 0 marks a filled one, and an integer k, return the length of the longest contiguous window containing at most k rejections. This models the longest stretch of order flow you could safely backtest against before the venue's reject rate looks too unstable to trust.

Input:
outcomes = [0,1,0,1,1,0,0,1,0], k = 2
Output:
5
The window outcomes[4..8] = [1,0,0,1,0] has length 5 and contains exactly 2 rejections (at indices 4 and 7); no longer window stays at or under 2 rejections anywhere in the sequence.
Tap to reveal solution
Harddesignheap

Design a Single-Symbol Limit Order Book Matcher

Design a limit order book for one symbol supporting add_buy(order_id, price, qty) and add_sell(order_id, price, qty). Each call attempts to match immediately against resting orders on the opposite side, best price first and, at equal prices, oldest order first (price-time priority), and returns the list of fills as (matched_order_id, fill_price, fill_qty) tuples. Any unmatched remainder rests in the book for future orders to match against.

Input:
add_sell(1,101.0,50); add_sell(2,101.0,30); add_buy(3,101.0,60)
Output:
[(1, 101.0, 50), (2, 101.0, 10)]
Both resting sells are at the same price, so the incoming buy for 60 shares fills the OLDER order (id 1) completely first, then takes the remaining 10 shares from order 2, which keeps 20 shares resting.
Tap to reveal solution
Mediumdynamic-programmingstate-machine#309

Best Time to Buy and Sell with Cooldown

You may complete as many transactions as you like, but after you sell, you cannot buy on the next day (cooldown of one day). Maximize profit.

Input:
prices = [1,2,3,0,2]
Output:
3
Buy 1, sell 2, cooldown, buy 0, sell 2.
Tap to reveal solution
Mediumheap#295

Running Median of the Bid-Ask Midpoint From a Streaming Tick Feed

Given a stream of midpoint prices (floats) arriving one at a time, return, after each new price, the median of all prices seen so far.

Input:
prices = [100.0, 102.0, 101.0, 105.0]
Output:
[100.0, 101.0, 101.0, 101.5]
After each new price the median of everything seen so far is recomputed: {100}->100.0, {100,102}->101.0, {100,101,102}->101.0, {100,101,102,105}->101.5.
Tap to reveal solution
Mediumheaphash-map

Top-K Volume Movers With Streaming Updates

You receive a stream of (ticker, volume) updates where each update OVERWRITES that ticker's current volume (not adds to it). After each update, return the k tickers with the highest current volume, in descending order of volume, ties broken alphabetically by ticker.

Input:
updates=[("AAPL",100),("MSFT",200),("AAPL",150),("GOOG",300)], k=2
Output:
[["AAPL"], ["MSFT","AAPL"], ["MSFT","AAPL"], ["GOOG","MSFT"]]
After update 3, AAPL's volume is overwritten from 100 to 150 -- MSFT (200) still leads, so the top-2 stays [MSFT, AAPL] even though AAPL's own value changed. After update 4, GOOG's 300 overtakes both.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Longest Window With Realized Volatility Below a Threshold

Given an array of daily returns and a volatility cap, return the length of the longest contiguous subarray whose standard deviation is at most the cap. Standard deviation must be recomputed for the actual window in question, not approximated.

Input:
returns=[0.01,-0.01,0.02,-0.15,0.01,0.00,-0.01], cap=0.03
Output:
4
The window [0.01,0.00,-0.01] plus one more calm day, or the leading [0.01,-0.01,0.02] extended, tops out at length 4 once the -0.15 outlier is excluded -- including it in any window blows the std well past the cap.
Tap to reveal solution
Mediumdesignheap

Design a HIFO (Highest-In-First-Out) Tax-Lot Position Tracker

Design a tracker supporting buy(ticker, qty, price), which opens a new tax lot, and sell(ticker, qty), which closes lots using HIFO -- the highest-cost-basis lot is sold first, to minimize realized taxable gains (or maximize realized losses) each time. A sell may partially consume a lot and may span multiple lots. Return the list of (lot_price, qty_from_this_lot) consumed by the sell, in the order consumed.

Input:
buy('AAPL',100,150); buy('AAPL',50,180); buy('AAPL',30,160); sell('AAPL',60)
Output:
[(180, 50), (160, 10)]
HIFO sells the highest-cost lot first: the 180-cost lot (50 shares) is fully consumed first, then 10 more shares are needed, taken from the next-highest-cost lot at 160 -- the 150-cost lot is untouched, left for a later sell.
Tap to reveal solution
Harddesignheaphash-table

Design a Price-Time Priority Limit Order Matcher

Design a limit order book matcher for a single instrument supporting add_buy(order_id, price, qty), add_sell(order_id, price, qty), and cancel(order_id). An incoming order matches immediately against resting orders on the opposite side that it crosses, in price-time priority (best price first, then earliest arrival among ties), partially filling as needed; any unfilled remainder rests in the book. Each add_* call returns the list of fills it produced, as (resting_order_id, incoming_order_id, trade_price, trade_qty) tuples.

Input:
add_sell(1,101.0,50); add_sell(2,100.5,30); add_buy(3,101.0,60)
Output:
[(2,3,100.5,30), (1,3,101.0,30)]
The incoming buy at 101.0 crosses both resting sells. Best price first: order 2 (100.5) fills completely for 30, then the remaining 30 shares fill against order 1 at its own resting price of 101.0.
Tap to reveal solution
Mediumsliding-windowhash-map

Smallest Trade Window Covering Every Required Venue

You have a chronological list of fills, each tagged with the venue that executed it, and a set of required venues your smart-order-router must have touched at least once for a best-execution audit. Find the length of the shortest contiguous window of fills that includes at least one fill from every required venue. Return 0 if no such window exists.

Input:
venues=['A','B','A','C','B'], required={'A','B','C'}
Output:
3
The window [A,C,B] at indices 2-4 is the shortest containing all three required venues at least once; no window of length 2 can cover three distinct required venues.
Tap to reveal solution
Mediumsliding-windowmonotonic-dequeprefix-sum#862

Shortest Contiguous Window Needed to Recover a Drawdown

Given a day-by-day P&L array, find the length of the shortest contiguous window whose cumulative sum is at least a given target recovery amount. Return -1 if no such window exists.

Input:
pnl = [-5, 2, 1, 8, -3, 6], target = 9
Output:
2
The window [1, 8] sums to 9 in length 2 -- the shortest contiguous stretch whose combined P&L reaches the recovery target.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit With Unlimited Transactions, Short Selling Allowed

Given daily prices for one instrument, you may hold at most one unit of exposure at any time, but that exposure can be long (+1), short (-1), or flat (0), and you may flip position as many times as you like at the day's price with no fees. Return the maximum achievable profit.

Input:
prices = [5, 3, 8, 2, 9]
Output:
20
Flip position every day to always be on the right side of the next move: short 5->3 (+2), long 3->8 (+5), short 8->2 (+6), long 2->9 (+7). Total 2+5+6+7=20 -- exactly the sum of each day's absolute price move, since a free, instant flip lets you capture every single one.
Tap to reveal solution
Hardheap

Running Median of a Live Trade Price Stream

Design a data structure that processes a stream of trade prices one at a time via add_price(price), and can return the median of every price seen so far via find_median(), called after any number of additions, in better than O(n) time per call.

Input:
add_price(10); add_price(20); find_median(); add_price(30); find_median()
Output:
15.0, 20.0
After [10, 20] the median is the average of both middle values, 15.0. After [10, 20, 30] the middle value is 20.0.
Tap to reveal solution
Mediumsliding-window#1438

Longest Tick Window Where the Bid-Ask Spread Stays Below a Threshold

Given a tick-by-tick sequence of quoted spreads (ask minus bid), find the length of the longest contiguous window in which the difference between the largest and smallest spread observed is at most a given limit.

Input:
spreads = [8, 2, 4, 7], limit = 4
Output:
2
The window [2,4] has max-min = 2 (ok, length 2); [4,7] has max-min = 3 (ok, length 2). Any 3-tick window includes 8 paired with 2 or 4, giving a spread range above 4.
Tap to reveal solution
Hardprobability

Expected Number of Trades Until K Consecutive Winning Trades

Each trade independently wins with probability p. Given a target streak length k, return the expected number of trades needed until you observe k wins in a row for the first time.

Input:
p = 0.5, k = 2
Output:
6.0
The classic 'expected flips until two heads in a row' result for a fair coin is 6.
Tap to reveal solution
Mediumheapstreamingtop-k

Top-K Volume Movers (Streaming)

You receive a live stream of (ticker, volume) updates -- each update REPLACES that ticker's current volume, it is not a delta. At any point, return the K tickers with the highest current volume, in descending order. Support update(ticker, volume) and top_k() for a stream where the same ticker updates repeatedly throughout the day.

Input:
update('AAPL',100); update('MSFT',300); update('AAPL',500); top_k(2)
Output:
[('AAPL', 500), ('MSFT', 300)]
AAPL's second update replaces its volume, so the first (100) entry must not count toward top_k.
Tap to reveal solution
Harddesignheapqueue

Design a Price-Time Priority Order Matcher

Design a class OrderMatcher that supports limit_order(order_id, side, price, size), adding a resting BUY or SELL limit order that immediately attempts to match against the opposite side's best-priced, earliest-arrived orders (price-time priority), executing partial fills as needed and resting any unfilled remainder. Return the list of (buy_order_id, sell_order_id, fill_price, fill_size) trades produced by each call.

Input:
limit_order(1,"SELL",101,10); limit_order(2,"SELL",100,5); limit_order(3,"BUY",102,8)
Output:
[] then [] then [(3, 2, 100, 5), (3, 1, 101, 3)]
The incoming buy at 102 crosses both resting sells (both <= 102): it fills the better-priced order 2 first (5 @ 100), then the remaining 3 shares against order 1 (3 @ 101), leaving order 1 resting with 7 shares left and the buy order fully filled.
Tap to reveal solution
Mediumdynamic-programming#123

Maximum Profit With At Most Two Round-Trip Trades

Given daily prices, you may complete at most two buy-then-sell round trips, never holding more than one share at once (a sell must happen before the next buy). Return the maximum achievable profit.

Input:
prices = [3, 3, 5, 0, 0, 3, 1, 4]
Output:
6
Buy at 0, sell at 3 (profit 3), then buy at 1, sell at 4 (profit 3). Two round trips, total profit 3 + 3 = 6 -- the best achievable with at most two transactions.
Tap to reveal solution
Mediumheap

Top K Most Active Tickers in a Streaming Trade Tape

Design a class ActivityTracker with record(ticker) that ingests one trade event at a time for a ticker, and top_k(k) that returns the k tickers with the highest trade counts so far, in descending order of count.

Input:
record("AAPL"); record("MSFT"); record("AAPL"); record("GOOG"); top_k(2)
Output:
["AAPL", "MSFT"]
AAPL has count 2, MSFT and GOOG each have count 1. Among the two count-1 tickers, insertion order (MSFT before GOOG) breaks the tie, so the top 2 by count are AAPL then MSFT.
Tap to reveal solution
Harddynamic-programming

Maximum Stock Profit With a Minimum Holding Period

Given daily stock prices and an integer m, unlimited transactions are allowed, but once you buy you are not permitted to sell until at least m full days have passed (you may hold longer than m days if you choose). Find the maximum achievable total profit.

Input:
prices=[1, 2, 10, 3, 9], m=2
Output:
8
Buying on day 0 (price 1) and being forced to hold at least 2 days rules out selling on day 1; selling on day 2 (price 10) is allowed (held 2 days) and nets 9. Alternatively buying day 3 (price 3) and selling day 4 (price 9) is only a 1-day hold, not permitted. The best achievable plan is a single trip: buy day 0 at 1, sell day 2 at 10, profit 9 -- checking against day-4's price of 9 confirms 9 is in fact the max single-trip profit obeying the constraint, and no combination of multiple constrained trips beats it here.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Window Where Rolling Volatility Stays Below a Risk Threshold

Given an array of daily returns and a threshold, find the length of the longest contiguous subarray whose population standard deviation is strictly less than the threshold.

Input:
returns = [0.01,-0.01,0.02,0.15,-0.01,0.0,0.01], threshold = 0.05
Output:
4
The window [-0.01, 0.0, 0.01] after the 0.15 spike plus one more calm day, or similar runs around it, has std well under 0.05; any window that includes the 0.15 outlier blows past the threshold, capping the longest qualifying run at length 4 (the trailing calm stretch, with one extra day included from before it where it still qualifies).
Tap to reveal solution
Mediumprobabilitymarkov-chain

Expected Number of Ticks Until Three Consecutive Up-Ticks

A price moves up on each tick with probability p (independent of history) or down otherwise. Compute the expected number of ticks until you observe three consecutive up-ticks for the first time.

Input:
p=0.5
Output:
14.0
With a fair coin the expected number of flips to see 3 consecutive heads is the well-known closed form (2^(3+1) - 2) / (2 - 1) = 14 for p=0.5, matching the classic streak-waiting-time result.
Tap to reveal solution
Mediumdynamic-programming#309

Max Profit With Unlimited Trades and a One-Day Cooldown After Selling

Given a daily price array, you may buy and sell an unlimited number of times, but after selling you must wait one full day (a cooldown) before buying again. Return the maximum achievable profit.

Input:
prices = [1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown, buy at 0, sell at 2 (profit 2). Total profit 3 -- buying at 3 then immediately re-buying at 0 isn't allowed because of the cooldown day.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Long-Run Fraction of Time a Market Maker's Inventory Sits in Each State

A market maker's inventory transitions each tick between three states, Short, Flat, and Long, according to a given row-stochastic transition matrix P, where P[i][j] is the probability of moving from state i to state j on the next tick. Assuming the chain is ergodic, return the stationary distribution pi such that pi @ P equals pi and pi sums to 1.

Input:
P = [[0.6,0.3,0.1],[0.2,0.6,0.2],[0.1,0.3,0.6]] (rows/cols ordered Short, Flat, Long)
Output:
[0.2857, 0.4286, 0.2857]
Solving pi = pi @ P with pi summing to 1 gives pi1 = pi3 = 2/7 and pi2 = 3/7 by symmetry of the transition probabilities between Short and Long -- the chain spends the most long-run time Flat.
Tap to reveal solution
Mediumdesignmath

Design a Real-Time Sharpe Ratio Tracker

Design a class supporting add_return(r), which records a new daily strategy return, and sharpe(), which returns the current annualized Sharpe ratio (mean divided by standard deviation of all returns seen so far, scaled by sqrt(252)) in O(1) time per call, without storing or rescanning the full return history.

Input:
add_return(0.01); add_return(-0.005); add_return(0.02); sharpe()
Output:
an annualized Sharpe computed purely from running statistics
Mean, count, and sum of squared deviations are all maintained incrementally on each add_return call, so sharpe() is a constant-time read of those three running values rather than a rescan of stored history.
Tap to reveal solution
Mediumheapsorting

K Closest Trade Prices to a Reference Price

Given a list of executed trade prices and a reference price target, return the k trade prices closest to target, ordered from closest to farthest. Ties (equal distance) break toward the lower price.

Input:
prices=[100.0, 102.5, 99.0, 101.0, 98.0], target=100.5, k=3
Output:
[100.0, 101.0, 99.0]
Distances to target: 100.0->0.5, 101.0->0.5, 99.0->1.5, 102.5->2.0, 98.0->2.5. The two closest are 100.0 and 101.0, tied at distance 0.5; the tie-break sends the lower price (100.0) first. Third closest is 99.0.
Tap to reveal solution
Hardsliding-windowhash-map

Shortest Window Containing a Quote From Every Venue

Given a chronological list of quote updates, each tagged with the venue that sent it, and the set of all distinct venue ids a smart-order-router must hear from before it can compute a consolidated best price, return the length of the shortest contiguous window of updates that contains at least one quote from every venue.

Input:
venues=[1, 2, 1, 3, 2, 1], all_venues={1, 2, 3}
Output:
3
The window at indices 1-3, [2, 1, 3], contains all three venues and has length 3. No shorter window can work, since a valid window needs at least one update from each of the 3 distinct venues.
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most K Buy/Sell Transactions

Given daily prices for one instrument and an integer k, you may complete at most k buy-then-sell round trips (never holding more than one unit at a time, and you must sell before buying again). Return the maximum total profit.

Input:
k = 2, prices = [3,2,6,5,0,3]
Output:
7
Buy at 2, sell at 6 for profit 4 (one transaction). Buy at 0, sell at 3 for profit 3 (a second transaction). Total 4 + 3 = 7, using both allowed transactions.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Probability of Eventual Default in a Credit Rating Migration Chain

You're given a credit rating transition matrix over n non-default ratings plus two absorbing outcomes, Default and Paid-Off: each year, a bond in rating i moves to rating j with probability trans[i][j], or is absorbed into Default with probability default_prob[i], or into Paid-Off with the remaining probability (each row of non-default probabilities plus default_prob plus paidoff_prob sums to 1). Given a starting rating, return the probability the bond is eventually absorbed into Default rather than Paid-Off, over an infinite time horizon.

Input:
trans=[[0.8,0.1],[0.2,0.5]], default_prob=[0.02,0.1], start=0
Output:
0.25
Using the fundamental matrix N=(I-Q)^-1 of the transient sub-chain Q=trans, the probability of absorption into Default from state i is row i of N dotted with the direct one-step default-probability vector; here that evaluates to 0.25 starting from state 0.
Tap to reveal solution
Harddynamic-programmingprefix-sum#1477

Maximum Combined P&L From Two Non-Overlapping Trading Windows of Fixed Lengths

Given a daily P&L array and two window lengths, firstLen and secondLen, choose a length-firstLen window and a length-secondLen window that do not overlap (in either order) to maximize their combined sum.

Input:
pnl = [2,1,5,6,0,9,5], firstLen = 1, secondLen = 2
Output:
20
The length-1 window [9] (index 5) and the length-2 window [5,6] (indices 2-3) do not overlap and sum to 9 + 11 = 20, the best achievable combination.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Rolling High-Low Band Over a Sliding Window

Given an array of tick prices and a window size k, return an array where each element is the (max - min) price range over the trailing k ticks ending at that index (or None for indices before the window first fills).

Input:
prices=[10,12,9,15,13,8], k=3
Output:
[None, None, 3, 6, 6, 7]
Index 2 window [10,12,9]: max-min=12-9=3. Index 3 window [12,9,15]: 15-9=6. Index 5 window [15,13,8]: 15-8=7.
Tap to reveal solution
Hardprobabilitymarkov-chain

Gambler's Ruin: Probability of Hitting a Target Bankroll

A trader starts with i units of capital, 0 < i < N, and repeatedly makes unit bets: wins with probability p (capital +1) or loses with probability q = 1-p (capital -1). Betting stops at 0 (ruin) or N (target reached). Give the probability of reaching N before 0, as a function of p, i, N -- and describe how you'd sanity-check the formula.

Input:
p=0.5, i=50, N=100
Output:
0.5
Fair game: the symmetric random walk gives P(reach N) = i / N.
Input:
p=0.47, i=50, N=100
Output:
~0.018
A tiny house edge compounds brutally over a long walk -- the classic reason 'just play longer to even out variance' is backwards with a negative edge.
Tap to reveal solution
Hardprobabilityrandom-walkmath

Expected Number of Trades to Reach a Profit Target

A market maker's inventory P&L moves by +1 tick with probability p and -1 tick with probability 1-p on each trade, independently. Starting at P&L 0, compute the EXPECTED number of trades until the P&L first reaches either +takeProfit (take profit) or -stopLoss (stop loss). Do not simulate -- give a closed-form computation.

Input:
p=0.5, take_profit=3, stop_loss=3
Output:
9.0
A fair walk with symmetric barriers a distance of 3 on either side: the classic gambler's-ruin duration formula gives distance-to-lower times distance-to-upper, 3*3=9.
Tap to reveal solution
Hardsliding-windowmonotonic-deque

Longest Window Where Price Stays Within a Volatility Band

Given a chronological list of prices and a maximum allowed band width, find the length of the longest contiguous window where the difference between the window's highest and lowest price does not exceed the band width.

Input:
prices=[8, 2, 4, 7], limit=4
Output:
2
Window [2,4] has range 2 and window [4,7] has range 3, both within limit=4, each length 2. No length-3 window stays within the band: [8,2,4] has range 6, [2,4,7] has range 5.
Tap to reveal solution
Harddesignheaporder-book

Limit Order Book Matching Engine (Price-Time Priority)

Design an order book supporting add_order(side, price, qty). Incoming buy orders match against resting sell orders priced at or below the limit, best price first; incoming sell orders match against resting buys priced at or above the limit, best price first. Within a price level, earlier orders fill first (time priority). Any unmatched quantity rests in the book. Return the list of fills produced by the new order.

Input:
sell 10@101, sell 5@100, then buy 8@101
Output:
fills: 5@100, 3@101; 7 shares rest resting on the 101 ask
The buy crosses the better (lower) ask price first, then the next-best price, price-time priority throughout.
Tap to reveal solution
Mediumheapmerge

Merge K Sorted Trade Print Streams by Timestamp

You receive trade prints from K different exchange feeds. Each feed's own list of (timestamp, price) prints is already sorted by timestamp ascending, but the feeds arrive as separate lists. Merge all K feeds into a single list of trades sorted by timestamp ascending across the whole market.

Input:
feeds = [[(1,100),(4,101)], [(2,99),(3,102),(9,103)], [(5,104)]]
Output:
[(1,100),(2,99),(3,102),(4,101),(5,104),(9,103)]
Each of the 3 feeds is individually sorted by timestamp; the merged output interleaves all of them into one globally sorted-by-timestamp stream.
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most K Round-Trip Trades

Given daily prices and a limit of at most k buy-sell round trips (no overlapping holdings -- must sell before buying again), return the maximum achievable profit.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 for a profit of 4; buy at 0, sell at 3 for a profit of 3. Total profit 7, using exactly 2 of the allowed transactions.
Tap to reveal solution
Mediumheaphash-map#347

Top K Most Active Tickers by Cumulative Volume

Given a stream of (ticker, volume) ticks arriving in time order and an integer k, return, after each tick, the current top k tickers ranked by TOTAL volume traded so far.

Input:
ticks = [('AAPL',100),('MSFT',50),('AAPL',80),('GOOG',200)], k = 2
Output:
['GOOG', 'AAPL']
Cumulative volumes end at AAPL=180, MSFT=50, GOOG=200, so after the last tick the top 2 by total volume are GOOG then AAPL.
Tap to reveal solution
Mediumheapk-way-merge#23

Merge K Sorted Trade Feeds Into One Timestamp-Ordered Stream

You receive trade prints from k separate exchange feeds, each already sorted by timestamp internally. Merge all k feeds into one list sorted by timestamp.

Input:
feeds = [[(1,'A'),(5,'A')], [(2,'B'),(3,'B')], [(4,'C')]]
Output:
[(1,'A'), (2,'B'), (3,'B'), (4,'C'), (5,'A')]
Each feed is internally sorted; merging by timestamp across all three gives one fully-ordered stream without ever re-sorting the whole thing from scratch.
Tap to reveal solution
Mediumheapgreedy

Order Routing Scheduler with Per-Venue Cooldown

You have a batch of child orders to route, each tagged with a destination venue. Because of exchange throttling rules, once you send an order to a given venue you must wait a cooldown of c time slots before sending another order to that SAME venue (orders to other venues are unaffected). Each time slot you may send exactly one order (or idle). Return the minimum number of time slots needed to send every order, respecting the cooldown per venue.

Input:
orders = ["NYSE","NYSE","NYSE","NASDAQ","NASDAQ","NASDAQ"], cooldown = 2
Output:
8
One valid order is NYSE, NASDAQ, idle, NYSE, NASDAQ, idle, NYSE, NASDAQ -- the busiest venue (NYSE, sent 3 times) forces at least two idle slots between its repeats, and NASDAQ having the same count means no idle slot can be filled by it either.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Run of Trades Within a Notional Budget

Given an array of trade notional sizes (all positive) in execution order and a capital budget, return the length of the longest contiguous run of trades whose total notional does not exceed the budget.

Input:
notionals = [5, 10, 5, 10, 5], budget = 25
Output:
3
The window [10, 5, 10] sums to 25, and no longer contiguous window stays within the budget.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Maximum High-Low Range Over Any Fixed-Length Window of Ticks

Given an array of tick prices and a window length w, return the maximum (max - min) range achieved by any contiguous window of exactly w consecutive ticks. This models scanning a session for its most volatile w-tick stretch.

Input:
prices = [4,2,9,1,7,3], w = 3
Output:
8
Windows of length 3: [4,2,9] range 7, [2,9,1] range 8, [9,1,7] range 8, [1,7,3] range 6. The maximum range across all of them is 8.
Tap to reveal solution
Hardheapsliding-window

Sliding Window Median of Order Sizes Using Two Heaps

Given a stream of order sizes and a window length k, return the median order size for every window of k consecutive orders as the window slides one order at a time.

Input:
orders=[10,20,30,40,50], k=3
Output:
[20, 30, 40]
Window [10,20,30] has median 20; window [20,30,40] has median 30; window [30,40,50] has median 40.
Tap to reveal solution
Harddynamic-programmingstate-machine

Best Trading Profit With a Mandatory T+1 Settlement Cooldown

Given daily prices for one instrument, you may make as many trades as you like (buy, later sell), but after SELLING you must wait exactly one full day before you are allowed to buy again -- a T+1 settlement cooldown on the sale proceeds. You may still buy on the day right after a cooldown day, just never on the day immediately following a sell itself. Return the maximum total profit achievable.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy on day 0 at 1, sell on day 1 at 2 (profit 1); day 2 is the mandatory cooldown; buy on day 3 at 0, sell on day 4 at 2 (profit 2). Total profit 1 + 2 = 3, which is optimal.
Tap to reveal solution
Mediumdesign

Design a Token-Bucket Rate Limiter for Order Submission

Design a class RateLimiter(capacity, refill_rate) with allow(timestamp) that returns True and consumes one token if a token is available at that timestamp, or False otherwise. Tokens refill continuously at refill_rate tokens per second, up to capacity, and timestamps arrive as monotonically non-decreasing floats (seconds).

Input:
RateLimiter(capacity=3, refill_rate=1); allow(0.0)x3; allow(0.1); allow(1.1)
Output:
True, True, True, False, True
Bucket starts full at 3 tokens. Three calls at t=0.0 drain it to 0. At t=0.1, only 0.1 tokens have refilled (not enough for a whole token), so the 4th call is rejected. By t=1.1, a full second has passed since the bucket hit 0, refilling exactly 1 token, so the 5th call succeeds.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Days Until Two Consecutive Winning Days

Each trading day is independently a winning day with probability p, otherwise a losing day. Return the expected number of days until you first observe two consecutive winning days.

Input:
p=0.5
Output:
6.0
This is the classic 'expected coin flips until two heads in a row' result: for a fair coin the expected wait is exactly 6 days.
Tap to reveal solution
Harddynamic-programming#123

Best Time to Buy and Sell Stock III (At Most Two Transactions)

Complete at most two transactions to maximize profit. You must sell before buying again -- no overlapping positions.

Input:
prices = [3,3,5,0,0,3,1,4]
Output:
6
Buy at 0, sell at 3 (profit 3); buy at 1, sell at 4 (profit 3); total 6.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit With a Flat Transaction Fee Per Round Trip

Given daily prices for one instrument and a flat fee charged once per completed round trip (buy then sell), return the maximum achievable profit. Any number of round trips is allowed, but you cannot hold more than one unit at a time.

Input:
prices = [1, 3, 2, 8, 4, 9], fee = 2
Output:
8
Buy at 1, sell at 8: profit 7 minus fee 2 = 5. Buy at 4, sell at 9: profit 5 minus fee 2 = 3. Total profit 8.
Tap to reveal solution
Mediumdesign

Design: Average-Cost Position Tracker With Realized and Unrealized P&L

Design a PositionTracker that processes fills one at a time via fill(side, qty, price), where side is 'BUY' or 'SELL'. It should track the current net position (positive for long, negative for short), the average cost basis of that open position, the cumulative realized P&L from any closing trades (using the average-cost method), and support unrealized_pnl(mark_price) for the open position against a given mark.

Input:
fill("BUY", 100, 50.0); fill("SELL", 40, 60.0)
Output:
position=60, avg_cost=50.0, realized_pnl=400.0
Buying 100 @ 50 opens a 100-long position with avg cost 50. Selling 40 @ 60 closes 40 units of that position, realizing 40 * (60 - 50) = 400 profit, leaving 60 units still open at the unchanged avg cost of 50.
Tap to reveal solution
Mediumdesignhash-maplinked-list

Design an LRU Cache for Recent Instrument Quotes

Design a fixed-capacity cache for the most recently accessed instrument quotes: get(symbol) returns the cached quote or -1 if absent (and marks it as recently used), and put(symbol, quote) inserts or updates a quote, evicting the least-recently-used symbol if the cache is at capacity. Both operations must run in O(1), matching the access pattern of a hot-path quote cache sitting in front of a slower reference-data lookup.

Input:
capacity=2; put(A,1), put(B,2), get(A), put(C,3), get(B), put(D,4), get(A), get(C), get(D)
Output:
1, -1, -1, -1, 4
get(A) after put(C,3) evicts B (least recently used at that point, since A was just touched by the get) is -1 as expected; put(D,4) then evicts A itself (least recently used after B was evicted and C, A were both touched, but A hasn't been touched since before C was inserted) making the final get(A) also -1, while C and D remain cached.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Ticks Until K Consecutive Up-Ticks

Each price tick moves up with probability p, independent of prior ticks. Compute the expected number of ticks needed to observe a run of k consecutive up-ticks in a row (a simple momentum-confirmation trigger some strategies wait for before entering).

Input:
p=0.5, k=3
Output:
14.0
With a fair coin, the expected number of flips to see 3 heads in a row is the classic result sum(2^i for i=1..3) = 2+4+8 = 14.
Tap to reveal solution
Mediumsliding-window

Shortest Contiguous Window of Ticks Whose Volume Reaches a Target

Given an array of per-tick trade volumes and a target total volume, return the length of the shortest contiguous window of ticks whose volumes sum to at least target, or -1 if no window qualifies. This models finding the fewest consecutive prints needed to fill a target size.

Input:
volumes = [2,3,1,2,4,3], target = 7
Output:
2
The window [4,3] (indices 4-5) sums to 7 in just 2 ticks -- no shorter window reaches the target.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Transactions And A Flat Fee Per Trade

Given daily prices, a transaction limit k, and a flat fee charged once per completed round trip (one buy plus the matching sell), return the maximum achievable profit using at most k round trips.

Input:
prices = [3,2,6,5,0,3], k = 2, fee = 1
Output:
5
Buy at 2, sell at 6 for profit 4 minus fee 1 = 3; buy at 0, sell at 3 for profit 3 minus fee 1 = 2. Total 3 + 2 = 5, using both allowed round trips.
Tap to reveal solution
Mediumsliding-window

Longest Window of Price Changes With At Most K Direction Reversals

Given an array of daily price changes (each positive, negative, or zero) and an integer k, a 'reversal' occurs at index i (1 <= i < n) if changes[i] and changes[i-1] have strictly opposite signs (a zero never counts as a sign flip either way). Return the length of the longest contiguous subarray of changes containing at most k reversals.

Input:
changes = [1,2,-1,-3,4,5,-2], k = 1
Output:
4
The subarray [1,2,-1,-3] has exactly one reversal (between 2 and -1) and length 4. Any length-5 window straddles a second reversal and exceeds k = 1.
Tap to reveal solution
Hardprobabilitydynamic-programmingmarkov-chain

Expected Number of Trades Until a Win Streak of Length K

A trader wins each individual trade independently with probability p. Compute the EXPECTED number of trades until the first time you observe k consecutive wins in a row. Do not simulate -- give a closed-form computation.

Input:
p=0.5, k=2
Output:
6.0
The well-known closed form for a fair coin gives (1 - 0.5^2) / (0.5 * 0.5^2) = 0.75 / 0.125 = 6.0 expected trades to see two wins in a row.
Tap to reveal solution
Mediumdesignheaphash-map

Design a Streaming Top-of-Book Tracker

Design a class TopOfBook supporting add_order(order_id, side, price, size) to add a resting order, cancel(order_id) to remove one, and best(side) returning the current best (highest bid or lowest ask) price and total size resting at that price, or None if that side is empty.

Input:
add_order(1,"BUY",100,50); add_order(2,"BUY",101,30); best("BUY"); cancel(2); best("BUY")
Output:
(101, 30) then (100, 50)
The best bid is initially 101 with 30 shares; after cancelling order 2, the best bid falls back to 100 with 50 shares.
Tap to reveal solution
Harddesignheap

Design a Price-Time Priority Limit Order Matcher

Design a class supporting add_order(side, price, qty, order_id), which adds a buy or sell limit order and immediately matches it against resting opposite-side orders at or better than its price, in strict price-then-arrival-time priority, filling as much as possible and resting any unfilled remainder in the book. Return the list of (order_id, counterparty_id, fill_qty, fill_price) fills produced.

Input:
add_order('sell',100,50,'S1'); add_order('sell',99,30,'S2'); add_order('buy',101,60,'B1')
Output:
fills for B1: [('B1','S2',30,99), ('B1','S1',20,100)]; B1 has 10 qty resting unfilled at 101
Tap to reveal solution
Mediumsliding-window#76

Shortest Tick Window Containing a Trade in Every Basket Symbol

Given a tick-by-tick sequence of symbols traded (one per tick) and a required basket of distinct symbols, return the shortest contiguous window of ticks that contains at least one trade in EVERY symbol in the basket. Return an empty list if no such window exists.

Input:
ticks = ['AAPL','MSFT','AAPL','GOOG','MSFT'], basket = {'AAPL','GOOG'}
Output:
['AAPL', 'GOOG']
The window at indices 2-3 (AAPL, GOOG) has length 2 and covers the whole basket. No window of length 1 can, since no single tick trades both required symbols.
Tap to reveal solution
Mediumheap

Merge K Sorted Order-Flow Tapes Into One Time-Ordered Stream

You receive K separate trade tapes (one per exchange feed), each already sorted ascending by timestamp. Merge all K tapes into a single timestamp-sorted list of (timestamp, exchange_id, price) tuples.

Input:
tapes = [[(1,'A',100.0),(5,'A',101.0)], [(2,'B',99.5),(4,'B',99.8)], [(3,'C',100.2)]]
Output:
[(1,'A',100.0),(2,'B',99.5),(3,'C',100.2),(4,'B',99.8),(5,'A',101.0)]
A standard k-way merge: at every step emit whichever tape's current front event has the smallest timestamp, then advance only that tape.
Tap to reveal solution
Mediumheapsorting

K Closest Trades to a Reference Price

Given an array of trade prices and a reference price, return the k trade prices closest to the reference price, in any order. If two prices are equally close, the smaller one is considered closer.

Input:
prices=[10, 7, 13, 9, 15], ref=10, k=2
Output:
[9, 10]
Distances from 10: |10-10|=0, |7-10|=3, |13-10|=3, |9-10|=1, |15-10|=5. The two closest are 10 (distance 0) and 9 (distance 1).
Tap to reveal solution
Mediumprobabilitydynamic-programming

Expected Number of Trades Until N Consecutive Winning Trades

A trader wins each independent trade with probability p. Given p and an integer n, return the expected number of trades until the first time n consecutive wins occur in a row. Return the answer rounded to 4 decimal places.

Input:
p = 0.5, n = 2
Output:
6.0000
This is the classic expected-waiting-time-for-a-streak result: the expected number of trades to see 2 consecutive wins with p = 0.5 is 1/p + 1/p^2 = 2 + 4 = 6.
Tap to reveal solution
Hardsortingbinary-searchlongest-increasing-subsequence#354

Russian Doll Envelopes (LIS variant)

Given pairs (w, h), find the maximum number that can be nested (each must be strictly wider AND taller). A classic quant interview question dressed up.

Input:
envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output:
3
[2,3] -> [5,4] -> [6,7]
Tap to reveal solution
Mediumheap

K Closest Trade Prices to the Day's VWAP

Given an array of trade prices executed during the day and a target value equal to the day's VWAP (volume-weighted average price), return the k prices closest to the VWAP. Ties (equal distance) break toward the smaller price. The order of the result does not matter.

Input:
prices = [90, 95, 101, 99, 110, 85], vwap = 100, k = 3
Output:
[95, 99, 101]
Distances from 100: 90->10, 95->5, 101->1, 99->1, 110->10, 85->15. The three smallest distances belong to 101 (1), 99 (1), and 95 (5) -- 90 and 110 tie at distance 10 but both lose to 95's smaller distance of 5, and 85 is farthest at 15.
Tap to reveal solution
Mediumprobability

Probability of Ruin in a Biased Random Walk

A trader's account P&L moves up by 1 unit with probability p or down by 1 unit with probability (1-p) each step, starting at 0. Given a stop-loss at -S units (ruin) and a take-profit at +T units, return the probability the account hits the stop-loss before the take-profit.

Input:
p = 0.5, stop_loss = 4, take_profit = 6
Output:
0.6
For a fair walk, the ruin probability from a symmetric random walk with barriers at -S and +T is simply T / (S + T) = 6/10 = 0.6.
Tap to reveal solution
Mediumprobabilitymarkov-chainmath

Probability of Hitting Take-Profit Before Stop-Loss

A position's mark-to-market P&L moves in discrete unit ticks: up one tick with probability p, down one tick with probability 1-p, independently each tick. Starting at P&L 0, the position is closed the instant P&L first hits either +a ticks (take-profit) or -b ticks (stop-loss). Compute, in closed form -- no simulation -- the probability that take-profit is hit first.

Input:
a=3, b=2, p=0.5
Output:
0.4
For a fair walk (p=0.5) the general gambler's-ruin formula has a removable 0/0 singularity whose limit is the simple linear ratio b / (a + b) = 2/5 = 0.4.
Input:
a=3, b=2, p=0.6
Output:
0.6398
With p != 0.5, use the ratio q/p raised to the barrier distances in the general closed form; the upward drift raises the take-profit probability well above the fair-coin value of 0.4.
Tap to reveal solution
Harddesignheap

Design a Price-Time Priority Order Matching Engine

Design a class OrderBook supporting add_buy(order_id, price, size) and add_sell(order_id, price, size). Each new order first tries to MATCH against the resting book on the opposite side at or better than its own price, in strict price-then-time priority, consuming resting size (partially filling a resting order if it's bigger than the incoming remainder) before any unfilled remainder joins the book as a new resting order. Return the list of fills produced by each call, as (resting_order_id, incoming_order_id, price, size) tuples.

Input:
book=OrderBook(); book.add_sell(1,100.0,10); book.add_sell(2,100.0,5); book.add_buy(3,100.0,12)
Output:
[(1, 3, 100.0, 10), (2, 3, 100.0, 2)]
Order 3 wants to buy 12 at 100.0. It matches resting order 1 first (arrived first at the same price -- time priority), fully consuming its 10, then matches 2 ticks more size out of order 2's remaining 5, leaving order 2 resting with 3 left and nothing left of order 3 to rest.
Tap to reveal solution
Mediumdesign

Design a Position Tracker With Weighted-Average Cost Basis

Design a class PositionTracker with trade(qty, price) (qty positive for a buy, negative for a sell) that maintains a running share position and its weighted-average cost basis, and realized_pnl() returning cumulative realized P&L so far. A buy that adds to an existing position (same sign) updates the average cost as a size-weighted blend of the old and new cost. A sell (or a buy that reduces/flips an existing position) realizes P&L against the CURRENT average cost for the portion that closes, and if it overshoots past flat, the remainder opens a fresh position at the trade's own price with no blending.

Input:
trade(100, 10.0); trade(50, 12.0); trade(-120, 15.0); realized_pnl()
Output:
520.0
Buy 100 @ 10 -> position 100 @ avg cost 10.0. Buy 50 @ 12 -> position 150 @ blended avg cost (100*10 + 50*12)/150 = 10.6667. Sell 120 @ 15 closes 120 of the 150 shares, realizing (15 - 10.6667)*120 = 520.0 of P&L against the average cost, leaving 30 shares still open @ avg cost 10.6667.
Tap to reveal solution
Hardheap#378

Kth Smallest Spread in a Row- and Column-Sorted Basis Matrix

You have an n x n matrix of cross-asset basis spreads where each row and each column is sorted in ascending order (a structure that falls out of a monotonic term-structure construction). Return the kth smallest spread in the matrix without materializing and sorting every entry.

Input:
matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Output:
13
Flattening and sorting every entry gives [1,5,9,10,11,12,13,13,15]; the 8th smallest (1-indexed) is 13.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit with a Mandatory One-Day Cooldown After Each Sale

Given daily closing prices, find the maximum profit from any number of buy-then-sell transactions (holding at most one unit at a time, must sell before buying again), with a compliance rule that after selling you cannot buy again the very next day -- you must sit out at least one day before re-entering.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), sit out the mandatory cooldown day (price 3), then buy at 0 and sell at 2 (profit 2), for a total of 3 -- buying on day 2 right after selling on day 1 is exactly what the cooldown forbids.
Tap to reveal solution
Mediumsliding-window

Shortest Window to Accumulate a Target Executed Volume

Given per-trade volumes for one name over a session (all positive) and a target total volume, return the length of the shortest contiguous subarray whose volumes sum to at least target, or -1 if no such window exists.

Input:
volumes=[100,50,200,100,50], target=300
Output:
2
The window [200,100] (indices 2-3) sums to 300, meeting the target with length 2 -- no shorter window reaches 300.
Tap to reveal solution
Easyheap

K Largest Realized P&L Trades From a Closed-Trade Log

Given a list of realized P&L values from a closed-trade log (one float per closed round-trip trade) and an integer k, return the k largest P&L values, in descending order.

Input:
pnls=[120.5, -30.0, 875.2, 40.0, -500.0, 210.0], k=3
Output:
[875.2, 210.0, 120.5]
The three largest realized P&Ls in the log, sorted descending -- the -500.0 and -30.0 losing trades and the 40.0 winner are all excluded since they don't make the top 3.
Tap to reveal solution
Mediumsliding-windowhash-map

Longest Trading Window With At Most K Halted Days

Given a boolean array halted where halted[i] is true if day i's session was halted (no trading), and an integer k, find the length of the longest contiguous window of days containing at most k halted days.

Input:
halted=[F,F,T,F,T,F,F], k=1
Output:
4
The window covering indices 0-3 ([F,F,T,F]) contains exactly one halted day, length 4. Extending further in either direction brings in a second halted day, which exceeds k=1.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window With a Bounded Intraday Price Range

Given a sequence of intraday prices and a threshold, find the length of the longest contiguous window where the range (max minus min within the window) does not exceed the threshold -- the longest 'quiet' consolidation period a range-breakout strategy might wait for before trading.

Input:
prices=[10,12,11,15,13,12], threshold=3
Output:
3
The window [15,13,12] has range 15-12=3 (valid, length 3); [10,12,11] has range 12-10=2 (also valid, length 3). No length-4 window keeps range <= 3, since extending either one pulls in a price more than 3 away from its extremes.
Tap to reveal solution
Mediumprobability

Probability a Market Maker's Inventory Hits a Risk Limit Before Flattening

A market maker's inventory moves by +1 with probability p (a buy fill) or -1 with probability 1-p (a sell fill) on each tick, starting at inventory 0. Given a risk limit L (a symmetric absolute inventory bound) and assuming the desk stops and flattens the instant inventory returns to 0 or hits +L or -L, return the probability inventory hits the limit (+L or -L) before returning to 0.

Input:
p = 0.5, L = 3
Output:
0.3333
After the mandatory first tick, inventory sits one step away from 0 (at +1 or -1) and L-1 steps away from the limit. For a fair (p=0.5) walk, gambler's ruin gives probability 1/L of reaching the far boundary before returning to 0 from a one-step-away state, so the answer is 1/3 regardless of which direction that first tick went.
Tap to reveal solution
Mediumdesign

Design a Position Tracker with Weighted-Average Cost Basis

Design a structure that tracks a single-symbol position through a stream of fills via trade(side, price, size) for side in {'buy','sell'}, maintaining a weighted-average cost basis, and reporting realized_pnl() (cumulative P&L booked from closing trades) and unrealized_pnl(mark_price) (paper P&L on the current open position at a given mark). A trade that increases or opens a position blends into the average cost; a trade that reduces or closes a position books realized P&L against the current average cost and leaves that average cost unchanged for any shares still open. A trade that flips the position from long to short (or vice versa) resets the average cost, for the new opposite-side remainder, to that trade's own price.

Input:
trade('buy',100,10); trade('buy',110,10); trade('sell',120,15)
Output:
avg_cost=105.0 before the sell; realized_pnl=225.0 and position=5 @ 105.0 after
The two buys blend to an average cost of (100*10 + 110*10) / 20 = 105.0. Selling 15 of the 20 held books realized P&L of 15*(120-105)=225.0 and leaves the remaining 5 shares at the SAME unchanged average cost of 105.0 -- a partial sell never touches the cost basis of the shares that stay open.
Tap to reveal solution
Hardprobabilitymarkov-chain

Probability a Market Maker's Inventory Random Walk Hits the Upper Barrier First

A market maker's inventory starts at s shares, with 0 < s < N, and each tick moves to s + 1 with probability p or s - 1 with probability 1 - p, until it is absorbed at either 0 or N. Given p, N, and s, return the probability the walk is absorbed at N (the upper barrier) rather than at 0.

Input:
p = 0.5, N = 4, s = 2
Output:
0.5
For an unbiased (p = 0.5) walk, the probability of hitting the upper barrier first is simply s / N: 2 / 4 = 0.5.
Input:
p = 0.4, N = 3, s = 1
Output:
0.211
With an unfavorable downward drift (p = 0.4), the biased closed-form expression gives roughly 0.211 -- noticeably below the naive s/N = 0.333 you'd get from ignoring the drift.
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most K Transactions and a Cooldown Day After Selling

Given an array of daily prices and an integer k, find the maximum profit achievable with at most k buy-sell transactions, where you may hold at most one share at a time, and after selling you must wait one full day (a cooldown) before you're allowed to buy again.

Input:
prices = [1, 5, 2, 7], k = 2
Output:
6
Buying at day 0 (price 1) and holding straight through to sell at day 3 (price 7) nets 6. Taking two smaller round trips instead -- buy day 0 sell day 1 for profit 4, then (after the forced cooldown on day 2) there's no day left to complete a second profitable trade -- only nets 4. The cooldown constraint makes the single long hold the better use of the two available transaction slots.
Tap to reveal solution
Mediumsliding-windowprefix-sum

Longest Run of Trading Days Under a Volume Participation Cap

Given daily traded volumes for a stock and a cap C, find the length of the longest contiguous run of days whose TOTAL volume does not exceed C.

Input:
volumes=[4,2,1,7,3], cap=8
Output:
3
The run [4,2,1] sums to 7 (<=8) and has length 3, the longest such run -- extending it to include 7 pushes the sum to 14, over the cap.
Tap to reveal solution
Easystackstring#20

Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Open brackets must be closed by the same type of brackets and in the correct order.

Input:
s = "()"
Output:
true
Input:
s = "()[]{}"
Output:
true
Input:
s = "(]"
Output:
false
Tap to reveal solution
Harddesign

Design a Limit Order Matching Engine (Price-Time Priority)

Design a class OrderBook with add_limit_order(order_id, side, price, size), where side is 'buy' or 'sell'. Match the incoming order against resting orders on the opposite side at or better than its price, filling at the RESTING order's price, in price-then-arrival-time priority, partially filling as needed; any unfilled remainder rests in the book. Return the fills produced by this call as (resting_order_id, incoming_order_id, price, filled_size) tuples.

Input:
add_limit_order(1,'sell',101,50); add_limit_order(2,'sell',100,30); add_limit_order(3,'buy',101,60)
Output:
[(2, 3, 100, 30), (1, 3, 101, 30)]
Order 3 is a buy at 101, willing to pay up to 101. The best resting ask is order 2 at 100 (better price than order 1's 101), so it fills first for all 30 of its shares at 100. The remaining 30 shares order 3 still needs are filled against order 1 at 101, leaving order 1 resting with 20 shares left at 101.
Tap to reveal solution
Mediumdynamic-programminggreedy

Best Time to Buy and Sell Stock With a Transaction Fee

Given daily prices and a fixed fee charged once per completed round trip, where you may hold at most one share at a time and make unlimited transactions, return the maximum achievable profit.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
8
Buy at 1, sell at 8: profit 8-1-2=5. Buy at 4, sell at 9: profit 9-4-2=3. Total 5+3=8, which beats any other combination of round trips.
Tap to reveal solution
Mediumheaptop-k

K Closest Trades to Arrival Price

Given a list of trade prices executed during a session and a reference arrivalPrice (the price your algo intended to trade at), return the k trade prices closest to arrivalPrice, in any order. Distance is the absolute difference. Do better than sorting the full list when k is much smaller than n.

Input:
prices=[101,95,103,99,107], arrival=100, k=3
Output:
[101, 99, 103]
Distances from 100 are 1, 5, 3, 1, 7 -- the three smallest belong to 101, 99, and 103.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Run of Trades With No Repeated Counterparty

Given a list of counterparty IDs for trades in execution order, return the length of the longest contiguous run of trades in which no counterparty appears more than once (a settlement-risk limit: you don't want too much exposure concentrated in one name within a short window).

Input:
counterparties = ["A", "B", "C", "A", "D"]
Output:
4
The window ["B", "C", "A", "D"] has length 4 with every counterparty appearing once; the first "A" has to drop out of the window once a second "A" shows up.
Tap to reveal solution
Harddynamic-programmingbinary-search#410

Split a Parent Order Into K Child Orders to Minimize the Largest Child's Volume

A parent order must be sliced into exactly k contiguous child orders (preserving sequence) against a series of planned trade clips. Given the clip sizes and k, return the minimum possible value for the largest child order's total volume, over all ways of grouping the clips into k contiguous child orders.

Input:
clips = [7, 2, 5, 10, 8], k = 2
Output:
18
Grouping as [7, 2, 5] and [10, 8] gives child totals 14 and 18; no other split into exactly 2 contiguous groups produces a largest child smaller than 18.
Tap to reveal solution
Easylinked-listtwo-pointers#206

Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Input:
head = [1,2,3,4,5]
Output:
[5,4,3,2,1]
Input:
head = []
Output:
[]
Tap to reveal solution
Mediumdynamic-programming

Max Profit With a One-Day Cooldown

Given daily prices for a stock, you may buy and sell any number of times (never holding more than one share at once), but after selling you must wait one full day (a cooldown) before buying again. Return the maximum achievable profit.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown on day index 2, buy at 0, sell at 2 (profit 2). Total profit 3.
Tap to reveal solution
Hardheapdesign

Rolling Median of a Streaming Mid-Price Feed

Design a data structure that ingests a stream of mid-prices one tick at a time via add_price(price) and can report the median of all prices seen so far via get_median() in better than linear time per call, matching a common building block for a robust (outlier-resistant) real-time price-level estimator.

Input:
add_price(5), add_price(2), get_median(), add_price(9), get_median()
Output:
3.5, 5.0
After [5, 2] the sorted order is [2, 5], so the median of two values is their average, 3.5. After adding 9 the sorted order is [2, 5, 9], so the median is the single middle value, 5.0.
Tap to reveal solution
Hardprobabilitymathdynamic-programming

Expected Number of Ticks Until a Random Walk Hits Target or Stop

A price moves in integer ticks from a starting level of 0: up one tick with probability p, down one tick with probability q=1-p, independently each tick. Given a profit target T ticks above and a stop loss S ticks below, return the expected number of ticks until the price first reaches +T or -S.

Input:
p=0.5, T=2, S=2
Output:
4.0
For a symmetric random walk between two absorbing barriers, the expected hitting time starting midway is S times T, here 2*2=4.
Tap to reveal solution
Mediumprobability

Gambler's Ruin: Probability of Hitting a Profit Target Before a Stop-Loss

A position's mark-to-market P&L moves up by 1 tick with probability p, or down by 1 tick with probability (1 - p), each step, starting at 0. Given a stop-loss level at -S ticks and a take-profit level at +T ticks (both positive integers), return the probability the P&L hits +T before it hits -S.

Input:
p = 0.5, stop_loss = 3, take_profit = 5
Output:
0.375
With a fair (p = 0.5) random walk, the classic gambler's-ruin result gives probability S / (S + T) = 3 / 8 = 0.375 of reaching the profit target before the stop-loss.
Tap to reveal solution
Mediumprobability

Expected Number of Trades Until a Market Maker's Inventory Hits a Risk Limit

A market maker's inventory starts at 0 shares. Each trade independently moves inventory by +1 (probability p, a buy order hits their offer) or -1 (probability 1-p). The desk must flatten the moment inventory reaches +N or -N (a hard risk limit on either side). Given p, N, and a starting inventory s with -N < s < N, return the expected number of trades until inventory first hits either limit.

Input:
p = 0.5, N = 3, s = 0
Output:
9.0
A symmetric random walk starting at the midpoint of a [-3, 3] absorbing range takes, in expectation, (N - s) * (N + s) = 3 * 3 = 9 steps to hit either barrier.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window Where Price Stays Within a Fixed Band (Two Monotonic Deques)

Given a sequence of daily prices and a band width W, find the length of the longest contiguous window during which max(price) - min(price) <= W -- i.e., the longest stretch the price stayed inside a trading range of width W.

Input:
prices=[1,5,2,3,8,1], W=4
Output:
4
The window covering indices 0-3 (prices 1,5,2,3) has max 5 and min 1, a range of 4 which fits the band; extending it to include 8 breaks the band since 8-1=7 exceeds 4, and no longer valid window exists elsewhere in the array.
Tap to reveal solution
Mediumdesignsliding-window

Design an Order Throttle Enforcing At Most N Orders Per Rolling Window

Design a class OrderThrottle(max_orders, window_ms) with a method allow(timestamp_ms) that returns True if submitting an order at that timestamp would keep the count of allowed orders within the last window_ms milliseconds at or below max_orders, and False otherwise (the order is throttled and not counted).

Input:
max_orders = 3, window_ms = 1000; allow(0), allow(200), allow(300), allow(900), allow(1100)
Output:
True, True, True, False, True
The first three orders (at 0, 200, 300) are all within any 1000ms window together, so the 4th at 900 would make 4 orders inside [0, 1000) and is throttled; by 1100 the order at 0 has fallen outside the trailing 1000ms window, freeing up a slot.
Tap to reveal solution
Mediumsliding-windowhash-map

Smallest Window Containing At Least K Distinct Tickers

Given a chronological list of ticker symbols from a consolidated trade tape and an integer k, return the length of the shortest contiguous window of trades that contains at least k distinct tickers. This models the minimum lookback a cross-sectional feature needs before it has enough breadth to compute reliably. Return 0 if no such window exists.

Input:
trades = ["AAPL","MSFT","AAPL","GOOG","MSFT","AMZN"], k = 3
Output:
3
The window at indices 1..3 (["MSFT","AAPL","GOOG"]) already contains 3 distinct tickers, and since 3 is the theoretical minimum possible length for 3 distinct tickers, no shorter window can beat it.
Tap to reveal solution
Mediumsliding-window

Longest Run of Consecutive Fills Within K Distinct Price Levels

Given a sequence of fill prices in execution order and an integer k, return the length of the longest contiguous run of fills that contains at most k distinct price levels.

Input:
prices = [1, 2, 1, 2, 3], k = 2
Output:
4
The run [1, 2, 1, 2] (indices 0-3) has exactly 2 distinct price levels and length 4; extending it to include the 3 at index 4 would push the distinct count to 3, which exceeds k.
Tap to reveal solution
Mediumprobability

Expected Number of Trades Until a Desk Has Triggered Every One of K Alpha Signals

A desk's execution system fires exactly one of k equally likely alpha signal types on every trade, independently each time. Return the expected number of trades needed until every one of the k signal types has fired at least once.

Input:
k = 4
Output:
8.3333
This is the coupon collector's problem: the expected count is k * (1 + 1/2 + 1/3 + ... + 1/k) = 4 * (1 + 0.5 + 0.3333 + 0.25) = 4 * 2.0833 = 8.3333.
Tap to reveal solution
Mediumheaphash-map

Top K Most Traded Symbols

Given an array of ticker symbols representing one trade log (one entry per fill), and an integer k, return the k symbols with the highest trade COUNT, ordered from most to least frequent. Break ties alphabetically (the symbol that sorts first wins the tie).

Input:
symbols=["AAPL","MSFT","AAPL","GOOG","MSFT","AAPL"], k=2
Output:
["AAPL", "MSFT"]
AAPL appears 3 times, MSFT 2 times, GOOG 1 time -- the two most frequent are AAPL then MSFT.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque#1438

Longest Window Where the Bid-Ask Spread Never Exceeds a Threshold

Given an array of mid-prices sampled at fixed intervals and an integer limit, return the length of the longest contiguous window where the difference between the window's maximum and minimum price never exceeds limit.

Input:
prices = [8,2,4,7], limit = 4
Output:
2
The window [4,7] has max 7, min 4, spread 3 <= 4, length 2. Extending to [2,4,7] gives spread 7-2=5 > 4, which is too wide, so 2 is the longest valid window here.
Tap to reveal solution
Harddesignqueue

Design a FIFO-Lot Position Tracker With Realized P&L

Design a class tracking a single instrument's position that supports trade(qty, price) (positive qty buys, negative qty sells) and realized_pnl(), returning cumulative realized profit and loss to date. Closing trades must be matched against opening lots on a FIFO basis: the oldest still-open lot is closed first, partial fills split a lot, and a trade that flips the position from long to short (or vice versa) closes out all existing lots before opening a new one on the other side.

Input:
trade(100,10.0); trade(50,12.0); trade(-120,11.0)
Output:
realized_pnl() -> 80.0
The sell of 120 consumes FIFO: the oldest lot (100 @ 10.0) closes first for a profit of 100*(11-10)=100, then 20 of the 50 @ 12.0 lot closes for 20*(11-12)=-20, leaving 30 still open at 12.0. Net realized profit is 100-20=80; closing the 12.0 lot first instead (ignoring FIFO order) would have given a different, wrong number.
Tap to reveal solution
Hardprobability

Probability of Hitting a Profit Target Before a Stop-Loss (Gambler's Ruin)

A strategy's P&L moves in discrete one-tick steps: up one tick with probability p, down one tick with probability q = 1 - p, each step independent of the last. Starting at P&L 0, return the probability the strategy hits +a (its profit target) strictly before it hits -b (its stop-loss).

Input:
p = 0.5, a = 3, b = 2
Output:
0.4
For a fair (p=0.5) random walk, the hit probability is simply b / (a + b) = 2 / 5 = 0.4 -- the walk is a martingale, so its expected stopping value must be zero, which pins down this exact ratio.
Tap to reveal solution
Mediumdesignsliding-window

Design a Rolling VWAP Tracker Over a Fixed Trailing Time Window

Design a class that ingests trade ticks add_trade(timestamp, price, volume) in non-decreasing timestamp order, and supports vwap(now) returning the volume-weighted average price over only the trades in the trailing window_seconds up to now, automatically expiring older trades. Assume vwap() is always called with a now >= the last added timestamp.

Input:
window_seconds=10; add_trade(1,100,50); add_trade(5,102,30); add_trade(12,101,20); vwap(12)
Output:
101.6
At time 12 with a 10-second window, the trade at t=1 (12-1=11 > 10) has expired; only t=5 (price 102, vol 30) and t=12 (price 101, vol 20) remain, giving VWAP = (102*30 + 101*20) / (30+20) = 101.6.
Tap to reveal solution
Mediumdesignheap

Design a Limit Order Book Top-of-Book Tracker

Design a class TopOfBook that supports add_order(order_id, side, price) where side is BUY or SELL, cancel_order(order_id) removing a previously added order, best_bid() returning the highest active BUY price (or None), and best_ask() returning the lowest active SELL price (or None).

Input:
add_order(1,"BUY",100); add_order(2,"BUY",102); add_order(3,"SELL",105); best_bid(); best_ask(); cancel_order(2); best_bid()
Output:
102, 105, 100
Best bid starts at 102 (the higher of 100/102), best ask at 105. After cancelling order 2 (the 102 bid), best bid falls back to 100.
Tap to reveal solution
Hardmarkov-chainprobabilitylinear-algebra

Long-Run Inventory Distribution of a Market Maker

A market maker's inventory, in lots, does a birth-death random walk on integer states -N..N. From any interior state i, inventory moves to i+1 with probability u (a buy fill), to i-1 with probability d (a sell fill), and stays at i with probability 1-u-d. At the boundaries +N and -N, the maker skews quotes hard enough to guarantee a move back toward zero: from +N it moves to N-1 with probability 1, and symmetrically from -N to -N+1 with probability 1. Given u, d, and N, return the long-run (stationary) probability of each inventory state.

Input:
N=1, u=0.5, d=0.5
Output:
[0.25, 0.5, 0.25]
For states -1, 0, 1: the boundary's forced pull-back combined with the interior's symmetric 50/50 walk yields a distribution that is symmetric and weighted toward the center inventory state 0.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With a Cooldown Day

Given daily prices for one instrument, you may buy and sell any number of times (never holding more than one unit at a time), but after selling you must wait one full day (a cooldown) before buying again. Return the maximum total profit.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy on day 0 at 1, sell on day 1 at 2 for a profit of 1. Day 2 is a forced cooldown after that sale. Buy again on day 3 at 0, sell on day 4 at 2 for a profit of 2. Total profit: 1 + 2 = 3, which beats any single round trip (the best single trip, buy at 0 and sell at 3, only earns 2).
Tap to reveal solution
Mediumsliding-window#1438

Longest Stretch Where Price Stays Within a Fixed Band of Its Own Range

Given a sequence of daily prices and a band width `limit`, return the length of the longest contiguous window during which the gap between the window's own highest and lowest price never exceeds `limit`. This is the longest stretch a volatility-band trigger would have stayed quiet.

Input:
prices = [8, 2, 4, 7], limit = 4
Output:
2
Window [2,4] has range 2 (ok), [4,7] has range 3 (ok, length 2 too), but [2,4,7] has range 5 > 4, and [8,2] has range 6 > 4 -- so the longest qualifying window has length 2.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position Tracker with Realized P&L

Design a position tracker for a single instrument supporting trade(side, price, quantity) for BUY or SELL fills, position() returning the current signed quantity held, and realized_pnl() returning the cumulative P&L booked so far. Closing trades must be matched against resting lots on strict FIFO basis (oldest lot closed first), and a single trade may partially close one lot and continue into the next; a trade larger than the entire resting book flips the position and opens a new lot in the new direction.

Input:
trade("BUY",100,10); trade("BUY",102,5); trade("SELL",105,12); position(); realized_pnl()
Output:
3, 56.0
Selling 12 closes the oldest lot first: 10 shares from the lot bought at 100 (profit (105-100)*10=50), then 2 shares from the lot bought at 102 (profit (105-102)*2=6), totaling 56.0 realized. The second lot still has 5-2=3 shares open, so the position is +3.
Tap to reveal solution
Mediumdynamic-programming

Max Profit With a Mandatory Cooldown Day After Selling

Given a sequence of daily prices for one stock, find the maximum profit from any number of buy-sell transactions (at most one share held at a time), with the rule that after selling you cannot buy again the very next day -- a one-day cooldown.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown on day index 2, buy at 0, sell at 2 (profit 2) -- total 3. Buying on day index 2 right after selling on day index 1 is not allowed.
Tap to reveal solution
Hardprobabilitymarkov-chaindynamic-programming

Probability a Random Walk Hits a Stop-Loss Before a Take-Profit

A position's mark-to-market P&L moves up by one tick with probability p or down by one tick with probability 1-p on each step, starting at 0. Given a stop-loss at -s ticks and a take-profit at +t ticks (both positive integers), compute the probability the stop-loss is hit before the take-profit.

Input:
p=0.5, s=3, t=5
Output:
0.625
With a fair coin this reduces to the classic gambler's ruin formula, which for p=0.5 gives simply t / (s + t) as the probability of hitting the stop first: 5 / (3 + 5) = 0.625.
Tap to reveal solution
Mediumdesignqueuesimulation

Position Tracker with FIFO Cost Basis

Design a PositionTracker for one symbol. trade(qty, price) records a fill -- positive qty is a buy, negative is a sell -- and returns the realized P&L from that fill, matching against the oldest open lots first (FIFO), including flipping from long to short or vice versa. Also support net_position() and unrealized_pnl(mark_price).

Input:
trade(100, 10.0); trade(50, 12.0); trade(-120, 15.0)
Output:
realized: 0, 0, 560.0; net_position() -> 30
The sell of 120 closes the 100-share @10 lot (100*(15-10)=500) then 20 of the 50-share @12 lot (20*(15-12)=60); 30 shares remain at cost basis 12.
Tap to reveal solution
Mediumheapgreedy

Scheduling Staggered Rebalance Orders Across a Cooldown Window

Given a list of rebalance tasks, each needing exactly one unit of execution time on a single trading desk, and a fixed cooldown of c time-units required between two executions of the SAME task type (to avoid overtrading the same name), return the minimum total time-units needed to execute all tasks, idling the desk if nothing is eligible.

Input:
tasks=['A','A','A','B','B','B'], cooldown=2
Output:
8
One valid schedule: A B idle A B idle A B, taking 8 slots. Each repeat of A or B must wait cooldown=2 slots after its previous execution; with two task types this thin, the desk cannot avoid idling.
Tap to reveal solution
Mediumsliding-windowhash-table

Longest Run of Trades With At Most K Distinct Tickers

Given a chronological list of ticker symbols traded (one per tick) and an integer k, return the length of the longest contiguous run of ticks that contains at most k distinct tickers.

Input:
tickers=["AAPL","AAPL","MSFT","MSFT","GOOG"], k=2
Output:
4
The window ["AAPL","AAPL","MSFT","MSFT"] (indices 0..3) has exactly 2 distinct tickers. Extending it to include GOOG would push the distinct count to 3, which exceeds k.
Tap to reveal solution
Mediumheap#295

Running Median of a Streaming Bid-Ask Spread

You receive a live stream of quotes, each given as (bid, ask) with ask >= bid. Each tick's spread is ask - bid. Implement a class SpreadTracker with add_quote(bid, ask), which processes one new quote, and median(), which returns the median of all spreads seen so far (the average of the two middle values when the count is even).

Input:
add_quote(99.98, 100.02); add_quote(99.95, 100.01); add_quote(100.00, 100.03); median()
Output:
0.04
The three spreads are 0.04, 0.06, and 0.03. Sorted, that's [0.03, 0.04, 0.06], whose middle value is 0.04.
Tap to reveal solution
Mediumsliding-window

Longest Order-Flow Window With At Most K Cancellations

Given a string of order-flow events where each character is 'A' (new order added) or 'C' (an order cancelled), return the length of the longest contiguous window of the stream containing at most K cancellation events.

Input:
events = "AACAACAAAC", k = 1
Output:
5
The window "CAAAC" has 2 cancels, too many. "AACAA" (indices 1-5) or "ACAAA" style windows with exactly one C work -- the longest valid window, e.g. indices 3-7 "ACAAA", has length 5 with exactly 1 cancel.
Tap to reveal solution
Mediumprobability

Stationary Distribution of a Three-Regime Market Model

A market is modeled as a Markov chain over three regimes -- risk-on, neutral, and risk-off -- with a given day-to-day transition probability matrix. Compute the long-run stationary distribution: the fraction of days the market spends in each regime over a very long horizon, assuming the chain is irreducible and aperiodic.

Input:
P = [[0.90, 0.08, 0.02], [0.20, 0.60, 0.20], [0.10, 0.30, 0.60]] (rows/cols ordered risk-on, neutral, risk-off)
Output:
[0.6173, 0.2346, 0.1481]
Even though risk-off is the 'stickiest' state in isolation (0.60 probability of staying put), the market still spends only ~15% of days there long-run, because it's rarely entered in the first place -- stickiness and long-run frequency are different things.
Tap to reveal solution
Mediumprobability

Steady-State Probability of Each Market Regime (Stationary Markov Distribution)

A market is modeled as switching daily between n regimes (e.g. Bull, Bear, Chop) according to a fixed Markov transition matrix P, where P[i][j] is the probability of moving from regime i to regime j the next day. Return the long-run (stationary) probability of being in each regime, assuming the chain is irreducible and aperiodic.

Input:
P = [[0.9, 0.075, 0.025], [0.15, 0.8, 0.05], [0.25, 0.25, 0.5]]
Output:
[0.625, 0.3125, 0.0625]
Solving pi = pi * P with pi summing to 1 gives roughly 62.5% Bull, 31.25% Bear, 6.25% Chop as the long-run time spent in each regime, regardless of which regime you start in.
Tap to reveal solution
Harddynamic-programming

Max Profit With Both a Cooldown and a Per-Trade Fee

Given daily prices for one stock, a fixed transaction fee charged once per completed round trip, and a one-day cooldown required after selling before you may buy again, find the maximum achievable profit from an unlimited number of transactions under both constraints simultaneously.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
6
Buying at 8 and selling at 4 is impossible (that's a loss), so the two visually tempting mid-sequence trades don't combine into anything profitable once the cooldown blocks re-entering right after a sale. The best achievable path is a single round trip: buy at 1, sell at 9, netting 9-1-2=6 -- more than the fee-only variant would extract from any two-trade split of this same sequence once the one-day cooldown is enforced.
Tap to reveal solution
Mediumsliding-window

Smallest Window of a Trade Tape Containing At Least K Distinct Tickers

Given a sequence of ticker symbols representing a trade tape (one ticker per trade, in order) and an integer k, return the length of the shortest contiguous window of the tape that contains at least k distinct tickers. Return -1 if no such window exists.

Input:
tape = ["AAPL","MSFT","AAPL","GOOG","MSFT"], k = 3
Output:
3
The window ["AAPL","GOOG","MSFT"] (indices 2-4) has 3 distinct tickers and length 3; no shorter window anywhere in the tape reaches 3 distinct tickers.
Tap to reveal solution
Mediumheap

K Largest Drawdowns from a Daily Equity Curve (Bounded Min-Heap)

Given a daily equity curve (a list of portfolio values) and an integer k, return the k largest drawdowns ever observed, where a drawdown at day i is defined as (running_peak_so_far - value[i]) / running_peak_so_far. You should not need to sort the full history of drawdowns to get the top k.

Input:
equity=[100, 110, 90, 95, 70, 130, 100], k=2
Output:
[0.3636, 0.2000]
Running peaks: 100,110,110,110,110,130,130. Drawdowns: 0, 0, (110-90)/110=0.1818, (110-95)/110=0.1364, (110-70)/110=0.3636, 0, (130-100)/130=0.2308. The two largest are 0.3636 (day 4) and 0.2308 (day 6), so with k=2 the closest matching pair by construction here is the two largest values from that list.
Tap to reveal solution
Mediumdynamic-programming#309

Best Time to Buy and Sell Stock With a One-Day Cooldown

Given daily prices for a stock, return the maximum profit from any number of buy-then-sell transactions (never holding more than one share at a time), with the rule that after selling you must wait one full day before buying again (a settlement cooldown).

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at index 0 (price 1), sell at index 1 (price 2) for profit 1, cooldown on index 2 (must skip a day before buying again), buy at index 3 (price 0), sell at index 4 (price 2) for profit 2. Total profit 1 + 2 = 3, beating the single trade buy@0 sell@2 (profit 2).
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Window of Trades Under a Volume Cap

Given a chronological list of per-trade volumes (each a positive integer) and an integer cap C representing a participation limit, return the length of the longest contiguous window of trades whose total volume does not exceed C.

Input:
volumes=[4,2,5,1,3], cap=8
Output:
3
The window [2,5,1] (indices 1-3) sums to exactly 8, the longest contiguous run whose total doesn't exceed the cap -- every length-4 window sums above 8.
Tap to reveal solution
Mediumheap

Top-K Most Active Tickers by Rolling Volume

You receive a stream of (ticker, volume) ticks, one per trade. Implement a class ActivityTracker with record(ticker, volume), which adds volume to that ticker's running total, and top_k(k), which returns the k tickers with the highest running total volume so far, sorted by volume descending (ties broken by ticker ascending).

Input:
record('AAPL', 100); record('MSFT', 300); record('AAPL', 250); record('GOOG', 200); top_k(2)
Output:
[('AAPL', 350), ('MSFT', 300)]
AAPL's running total is 100 + 250 = 350, MSFT is 300, GOOG is 200. The top 2 by volume are AAPL then MSFT.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Rolling Maximum Resting Bid Size Over a Sliding Time Window

Given an array of the best-bid resting size observed once per second, and a window length w seconds, return an array of the maximum resting size within each trailing w-second window as the window slides one second at a time across the array.

Input:
sizes=[5,3,8,8,2,9,1], w=3
Output:
[8,8,8,9,9]
Windows [5,3,8], [3,8,8], [8,8,2], [8,2,9], [2,9,1] have maxima 8, 8, 8, 9, 9 respectively.
Tap to reveal solution
Harddesignheap

Design a Price-Time-Priority Limit Order Book Matching Engine

Design a class OrderBook with add_limit_order(order_id, side, price, qty) ('buy' or 'sell') that matches the new order against the opposite side's best-priced, earliest-submitted resting orders (price-time priority), trading at the RESTING order's price, and rests any unfilled remainder on the book. Return the list of (resting_order_id, qty_filled, fill_price) fills produced. Also support best_bid() and best_ask(), each returning the best resting price on that side or None if empty.

Input:
add_limit_order("s1","sell",101.0,50); add_limit_order("s2","sell",100.5,30); add_limit_order("b1","buy",101.0,40)
Output:
[("s2", 30, 100.5), ("s1", 10, 101.0)] ; best_ask()=101.0 ; best_bid()=None
The incoming buy at 101.0 crosses the best (lowest) resting ask first: s2 at 100.5 fills completely for 30, then the remaining 10 of the buy fills against s1 at 101.0, leaving s1 resting with 40 left. The buy order itself is fully filled, so nothing rests on the buy side.
Tap to reveal solution
Hardprobabilitydynamic-programmingrandom-walk

Expected Number of Ticks Until an Inventory Random Walk Hits Either Risk Limit

A market maker's inventory moves by +1 with probability p (a buy fill) or -1 with probability 1-p on each incoming order, independent of history. Risk limits force a stop once inventory hits 0 or N. Starting from inventory i (0 < i < N), compute the expected number of ticks (order fills) until inventory first hits either boundary.

Input:
N=4, i=2, p=0.5
Output:
4.0
For a symmetric walk the expected time to absorption has the closed form i*(N-i): with i=2, N=4, that's 2*2=4.0 expected fills before hitting either boundary.
Tap to reveal solution
Hardprobability

Probability a Resting Quote Gets Picked Off Before an Auto-Cancel Barrier (Gambler's Ruin)

Your resting limit quote sits d ticks away from the current mid-price. Each discrete tick, the mid-price moves one tick CLOSER to your quote with probability p, or one tick FARTHER with probability 1-p. If the mid-price ever drifts n ticks farther away before reaching your quote, a risk system auto-cancels it (safe). Return the probability your quote gets picked off (the mid-price reaches it) before that cancellation.

Input:
d=3, n=10, p=0.5
Output:
0.7
A fair (symmetric) random walk between two absorbing barriers has a ruin probability linear in distance: starting 3 ticks from the pick-off barrier out of 10 total, the probability of reaching it first is (10-3)/10 = 0.7.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque#1438

Longest Window of Consecutive Prices Whose High-Low Range Stays Within a Band

Given an array of prices in time order and a limit, return the length of the longest contiguous subarray whose maximum value minus minimum value is at most limit.

Input:
prices = [8,2,4,7], limit = 4
Output:
2
The full array has range 8-2=6 > 4. The longest valid window is length 2, e.g. [2,4] or [4,7], each with range <= 4.
Tap to reveal solution
Hardsliding-windowhash-table

Shortest Window of Ticks Containing Every Required Order Type

Given a chronological list of order-type tags per tick (e.g. LIMIT, MARKET, CANCEL, ...) and a set of required order types that must all appear, return the shortest contiguous window of ticks that contains at least one of every required type, or None if no such window exists.

Input:
ticks=["LIMIT","MARKET","LIMIT","CANCEL","MARKET"], required={"MARKET","CANCEL"}
Output:
(3, 4)
The window ticks[3:5] = ["CANCEL","MARKET"] is the shortest contiguous window containing both required types.
Tap to reveal solution
Mediumdesignbinary-search

Design: Compute the Clearing Price of a Single-Price Call Auction

Given a list of buy orders and sell orders (each a (price, quantity) pair) submitted to a call auction, return the single clearing price that maximizes total matched volume, along with that matched volume. A buy order at price b is willing to transact at any clearing price <= b; a sell order at price s is willing to transact at any clearing price >= s. Among prices achieving the maximum volume, return the smallest such price.

Input:
buys = [(10,100),(9,200),(8,50)], sells = [(8,150),(9,100),(10,80)]
Output:
(9, 250)
At price 9, demand (buy orders priced >= 9) is 100 + 200 = 300 and supply (sell orders priced <= 9) is 150 + 100 = 250, so matched volume is min(300, 250) = 250 -- the best achievable across all three candidate prices (8, 9, 10).
Tap to reveal solution
Mediumdynamic-programming

Maximum P&L From Non-Adjacent Trading Days

You have a forecasted daily P&L, pnl[i], for each of N days (values can be negative). A risk rule forces a mandatory day off immediately after any day you trade, so you can never select two adjacent days. Choose a subset of non-adjacent days to trade, maximizing total P&L; days you skip contribute zero.

Input:
pnl=[5, -2, 8, 3, -1, 9]
Output:
22
Trade days 0, 2, and 5 (all non-adjacent): 5 + 8 + 9 = 22. Any selection touching adjacent days, or including the -2 or -1 days, does worse.
Tap to reveal solution
Hardsliding-window

Shortest Order-Flow Window Containing an Exact Required Multiset of Order Types

Given a stream of order-type characters and a required multiset of counts (e.g. needing at least 2 'L' (limit), 1 'M' (market), 1 'C' (cancel) orders), return the length of the shortest contiguous window of the stream that contains at least that many of each required type. Return 0 if no such window exists.

Input:
events = "LMLCLM", required = {"L": 2, "M": 1, "C": 1}
Output:
4
The window "LMLC" (indices 0-3) contains 2 L, 1 M, and 1 C -- exactly enough of each. No shorter window satisfies all three counts at once.
Tap to reveal solution
Mediumsliding-window#1493

Longest Window of Daily Returns Allowing At Most One Down Day

Given an array of daily returns (each positive, zero, or negative), return the length of the longest contiguous subarray that contains at most one day with a negative return.

Input:
returns = [1,-1,2,3,-1,4]
Output:
4
[2,3,-1,4] (indices 2-5) has exactly one negative day and length 4. [1,-1,2,3] (indices 0-3) is also length 4 with one negative. No contiguous window containing both negative days (indices 1 and 4) is valid, and no single-negative window reaches length 5 here.
Tap to reveal solution
Mediumdesignheap

Design a Top-of-Book Tracker With Order Cancellation

Design a class TopOfBook supporting add_order(order_id, side, price), where side is 'buy' or 'sell', cancel(order_id), which removes a previously added order, and best_bid() / best_ask(), which return the highest active buy price and lowest active sell price (or None if no active orders remain on that side).

Input:
add_order(1,'buy',100); add_order(2,'buy',105); add_order(3,'sell',110); best_bid(); cancel(2); best_bid()
Output:
105, then 100
Before cancel(2), the best (highest) active buy is order 2 at 105. After cancelling it, the best remaining active buy is order 1 at 100.
Tap to reveal solution
Mediumdesign

Design a Trade Blotter Supporting Insert and Timestamp Range Queries

Design a class TradeBlotter supporting record(timestamp, trade_id) where timestamps arrive out of order, and trades_between(start, end) returning the list of trade_ids with a timestamp in [start, end], in timestamp order.

Input:
record(100,'t1'); record(50,'t2'); record(150,'t3'); trades_between(60,120)
Output:
['t1']
Only t1's timestamp (100) falls within [60, 120]; t2 (50) is too early and t3 (150) is too late.
Tap to reveal solution
Mediumdynamic-programminggreedy

Maximum Profit With At Most One Buy-Sell Pair Per Calendar Month

Given daily prices each tagged with a (year, month) label, and the constraint that you may complete at most one buy-then-sell round trip within each calendar month (a position must be closed by month end, never carried across months), return the maximum total profit.

Input:
prices=[10,12,8,15], months=['2026-01','2026-01','2026-02','2026-02']
Output:
9
January: buy at 10, sell at 12, profit 2 -- the best single transaction within Jan's [10,12]. February: buy at 8, sell at 15, profit 7. Total 2+7=9, each month solved independently as its own single-transaction subproblem.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Buy/Sell Transactions

Given daily prices for a single stock and an integer k, you may complete at most k buy-then-sell transactions (you must sell before buying again -- no overlapping positions). Return the maximum total profit achievable.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 for a profit of 4. Buy at 0, sell at 3 for a profit of 3. Total: 7, achieved with exactly 2 transactions.
Tap to reveal solution
Harddesignheap

Design a Price-Time Priority Limit Order Book Matcher

Design a class OrderBook supporting add_order(order_id, side, price, qty) where side is 'buy' or 'sell', which attempts to match the new order against the opposite side's best-priced resting orders using price-time priority (best price first, earliest arrival among ties), executing trades and resting whatever quantity remains unfilled; and cancel(order_id), which removes a resting order if it hasn't fully filled yet. add_order should return a list of (resting_order_id, traded_qty, traded_price) execution tuples.

Input:
add_order(1, 'buy', 100.0, 10); add_order(2, 'sell', 99.0, 4)
Output:
[] then [(1, 4, 100.0)]
Order 1 rests fully (no asks exist yet). Order 2 crosses the book: it fills 4 shares against resting order 1 at order 1's price of 100.0, since the resting order was there first and sets the execution price.
Tap to reveal solution
Easyheapstreaming

Kth Largest Trade Size in a Live Stream

Design a class KthLargestTradeSize that is initialized with an integer k and a list of initial trade sizes, and supports add(trade_size), which inserts a new trade size and returns the kth largest trade size among all trades seen so far.

Input:
k=3, initial=[4,5,8,2]; then add(3), add(5), add(10), add(9), add(4)
Output:
[4, 5, 5, 8, 8]
After add(3): sorted desc [8,5,4,3,2], 3rd largest is 4. After add(5): [8,5,5,4,3,2], 3rd largest is 5. After add(10): [10,8,5,5,4,3,2], 3rd largest is 5. After add(9): [10,9,8,5,5,4,3,2], 3rd largest is 8. After add(4): still 8.
Tap to reveal solution
Harddynamic-programming#188

Best Time to Buy and Sell with at Most K Transactions

Complete at most k transactions to maximize profit.

Input:
k = 2, prices = [3,2,6,5,0,3]
Output:
7
Buy 2 sell 6, buy 0 sell 3.
Tap to reveal solution
Mediumsliding-windowhash-map#76

Smallest Window of Ticks Containing a Trade From Every Required Venue

Given a chronological list of venue codes (one per tick) and a set of required venues, return the length of the shortest contiguous window that contains at least one tick from every required venue. Return -1 if no such window exists.

Input:
ticks = ['NYSE','ARCA','NYSE','BATS','ARCA'], required = {'NYSE','BATS'}
Output:
2
ticks[2:4] = ['NYSE','BATS'] covers both required venues in a window of length 2 -- no shorter window does.
Tap to reveal solution
Harddesign

Design a Position Tracker With FIFO Lot Accounting for Partial Fills

Design a class PositionTracker that processes buy(price, size) and sell(price, size) calls against a single instrument and supports realized_pnl(), the cumulative realized P&L so far, and open_position(), the current net open size. Sells are matched against open buy lots on a FIFO basis (oldest lot first), and a sell may partially consume a lot or span multiple lots.

Input:
buy(100, 10); buy(102, 10); sell(105, 15); open_position(); realized_pnl()
Output:
5, 65
The sell of 15 consumes all 10 shares from the first lot (bought at 100) and 5 shares from the second lot (bought at 102): realized P&L = 10*(105-100) + 5*(105-102) = 50 + 15 = 65. Open position is the remaining 5 shares from the second lot.
Tap to reveal solution
Mediumheap

Running Median of a Streaming Price Feed

Design a class that ingests a stream of trade prices one at a time via add_price(price) and can return the median of all prices seen so far via get_median() in O(log n) per insertion and O(1) per query.

Input:
add_price(5); add_price(2); get_median(); add_price(8); get_median()
Output:
3.5, then 5
After [5,2], sorted is [2,5], median is their average 3.5. After [5,2,8], sorted is [2,5,8], median is 5.
Tap to reveal solution
Mediumdynamic-programminggreedy

Max Profit With a Flat Fee Per Round-Trip Trade

Given daily prices and a flat fee charged once per completed round-trip trade (buy then sell), with unlimited transactions allowed but no overlapping holdings, return the maximum achievable profit after fees.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
8
Buy at 1, sell at 8: profit 7, minus the 2 fee, nets 5. Buy at 4, sell at 9: profit 5, minus the 2 fee, nets 3. Total 5 + 3 = 8, more than any other combination once fees are accounted for.
Tap to reveal solution
Hardheap

Sliding-Window Median of the Last K Trade Prices

Given a stream of trade prices and a window size k, for every window of the k most recent trades (starting once k trades have occurred) return the median price of that window, in order.

Input:
prices = [1,3,2,5,4], k = 3
Output:
[2.0,3.0,4.0]
Window [1,3,2] -> sorted [1,2,3] -> median 2. Window [3,2,5] -> sorted [2,3,5] -> median 3. Window [2,5,4] -> sorted [2,4,5] -> median 4.
Tap to reveal solution
Harddesignheaporder-book

Design a Price-Time Priority Limit Order Book Matching Engine

Design a single-symbol limit order book supporting add_order(side, price, qty, order_id), which attempts to match the incoming order against resting orders on the opposite side using price-time priority -- best price first, and FIFO among orders tied at the same price -- producing a list of fills, then rests any unfilled remainder in the book at its price. Also support best_bid() and best_ask(), each returning the best resting price on that side (or None if empty).

Input:
add_order('buy',100,10,'o1'); add_order('sell',99,4,'o2'); best_bid(); best_ask()
Output:
fills=[('o2','o1',4,99)], best_bid=100, best_ask=None
The resting buy at 100 (o1, 10 shares) crosses the incoming sell at 99, since 99 <= 100. They trade 4 shares at the resting order's price of 99 (the earlier-priority side's price is what the trade prints at). o1 has 6 shares left resting at 100; o2 is fully filled, so best_ask is now empty.
Tap to reveal solution
Mediumprobabilitymath

Expected Number of Trades Until Two Consecutive Wins

Each trade wins independently with probability p. What is the expected number of trades until you first observe two consecutive winning trades?

Input:
p=0.5
Output:
6.0
The classic result for expected trials until a run of 2 successes with a fair coin is 6. More generally the closed form is (1 + p) / p^2, which gives (1 + 0.5) / 0.25 = 6.0.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Window Where Price Stays Within a Tolerance Band of VWAP

Given a sequence of (price, volume) trade ticks in execution order and a tolerance fraction, return the length of the longest contiguous run of ticks whose volume-weighted average price (VWAP), computed over just that window, stays within tolerance of every individual price inside the window.

Input:
prices = [100, 101, 99, 103, 100], volumes = [10, 10, 10, 10, 10], tolerance = 0.02
Output:
3
The window [100, 101, 99] has VWAP = 100.0 and every price in it is within 2% of 100.0; extending to include 103 breaks the 2% band, so 3 is the longest qualifying run.
Tap to reveal solution
Mediumprobabilitymath

Expected Number of Ticks to Flatten a Mean-Reverting Random-Walk Position

A trader's inventory starts at i lots (0 < i < N) and changes by +1 or -1 each tick with equal probability 0.5 each, independent across ticks. The position is flattened the instant it hits either boundary, 0 or N. Return the expected number of ticks until the position hits one boundary or the other.

Input:
i=2, N=5
Output:
6.0
For a fair (p=0.5) random walk between absorbing barriers 0 and N, the expected number of steps to absorption starting from i is exactly i*(N-i). With i=2, N=5, that's 2*3 = 6.0 ticks on average.
Tap to reveal solution
Harddesignheap

Design: Minimal Price-Time-Priority Limit Order Book

Design a LimitOrderBook supporting add_limit_order(order_id, side, price, size), where side is 'buy' or 'sell'. An incoming order matches against the opposite side at prices that cross (a buy matches asks at or below its price; a sell matches bids at or above its price), filling against the best-priced resting order first and, within a price level, the earliest-added resting order first (FIFO). Any unfilled remainder rests in the book. Return the list of fills produced, each as (resting_order_id, incoming_order_id, fill_price, fill_size).

Input:
add(1,'sell',101,50); add(2,'sell',100,30); add(3,'buy',102,40)
Output:
[], [], [(2,3,100,30), (1,3,101,10)]
Order 1 and order 2 rest as asks with no bids to cross. Order 3 (buy at 102, size 40) crosses: it first fills fully against the better-priced ask (order 2 at 100) for 30 units, then fills 10 more units against order 1 at 101, leaving order 1 resting with 40 units remaining and order 3 fully filled.
Tap to reveal solution
Mediumheap

Running Median of Resting Order Sizes in a Live Book

Design a class that ingests resting order sizes one at a time as orders arrive in a live book, and after each insertion reports the current median order size seen so far.

Input:
add(100); add(400); add(200); add(300); add(50)
Output:
100.0, 250.0, 200.0, 250.0, 200.0
After [100]: median 100.0. After [100,400]: median (100+400)/2 = 250.0. After [100,200,400]: median 200.0. After [100,200,300,400]: median (200+300)/2 = 250.0. After [50,100,200,300,400]: median 200.0.
Tap to reveal solution
Mediumdynamic-programmingknapsack

Selecting a Bounded-Risk-Budget Subset of Trade Ideas to Maximize Expected Alpha

You have a list of candidate trade ideas, each with an expected alpha (in basis points) and a risk cost (in units of your risk budget). You may take any subset, each idea at most once, but the total risk cost of the selected ideas must not exceed a fixed risk budget. Return the maximum total expected alpha achievable.

Input:
alpha=[60, 100, 120], risk_cost=[10, 20, 30], risk_budget=50
Output:
220
Taking ideas 1 and 2 gives alpha 100+120=220 at risk cost 20+30=50, exactly at budget -- better than all three (risk cost 60, over budget) or ideas 0 and 2 (alpha 180, risk cost 40, under budget but less alpha).
Tap to reveal solution
Hardprobabilityoptimal-stoppingmath

Accepting the Best Block Trade Offer Under Optimal Stopping (Secretary Problem)

n block trade offers arrive one at a time in a uniformly random order. You only observe each offer's rank relative to the ones already seen, not its true rank among all n, and must irrevocably accept or reject it on arrival. You want to maximize the probability of accepting the single BEST offer out of all n. Given n, find the optimal number of offers to observe-and-reject before switching to 'accept the next offer that beats everything seen so far,' and the resulting success probability.

Input:
n=4
Output:
reject the first 1, success probability = 11/24 ~ 0.4583
Observing 1 offer purely as a benchmark, then accepting the first subsequent offer that beats it, maximizes the chance of landing on the single best of the 4 -- beating the alternatives of accepting the very first offer blind, or rejecting 2 or 3 offers before switching.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position and Realized/Unrealized P&L Tracker

Design a class PositionTracker supporting trade(side, price, size), recording a BUY or SELL fill and updating realized P&L using FIFO lot accounting (the oldest open lot on the opposite side is closed first), and unrealized_pnl(mark_price), returning the mark-to-market P&L of whatever position remains open at the given mark price. You may assume a single trade never flips the net position from long to short or vice versa (a trade that would close the entire existing position exactly zeroes it out at most).

Input:
trade("BUY", 100, 10); trade("BUY", 105, 5); trade("SELL", 110, 8); unrealized_pnl(108)
Output:
realized_pnl = 80.0, unrealized_pnl(108) = 31.0
Buy 10@100, buy 5@105 (two open long lots). Sell 8 consumes FIFO: all 8 from the first lot (100), realized = (110-100)*8 = 80. Remaining open lots: 2@100, 5@105. Unrealized at mark 108: (108-100)*2 + (108-105)*5 = 16+15 = 31.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position Tracker With Average Cost Basis and Realized P&L

Design a class supporting buy(quantity, price), which opens a new cost-basis lot, and sell(quantity, price), which closes existing lots on a FIFO basis (oldest lot first) and returns the realized profit or loss from that sale. Also support avg_cost(), the quantity-weighted average price across all currently open lots.

Input:
buy(10,100); buy(5,110); avg_cost(); sell(12,120)
Output:
avg_cost() = 103.33, sell(...) = 220.0
avg_cost blends both lots: (10*100 + 5*110)/15 = 103.33. Selling 12 consumes all 10 shares from the first lot (profit 10*20=200) then 2 shares from the second lot (profit 2*10=20), for 220 total; 3 shares remain in the second lot.
Tap to reveal solution
Mediumheap

K Closest Trade Prices To A Reference Price

Given an array of trade prices and a reference price target, along with an integer k, return the k trade prices closest to target. If two prices are equally close, the smaller price comes first. You do not need to return them sorted by original order.

Input:
prices = [4.0, 1.0, 9.0, 3.0, 5.0], target = 4.5, k = 3
Output:
[4.0, 5.0, 3.0]
Distances from 4.5 are 0.5 (4.0), 3.5 (1.0), 4.5 (9.0), 1.5 (3.0), 0.5 (5.0). The 3 closest are 4.0 and 5.0 (tied at 0.5, smaller price first) then 3.0 (1.5).
Tap to reveal solution
Mediumprobabilitymath

Expected Number of Trades Until Three Consecutive Winning Trades

A trading strategy wins each individual trade independently with probability p. Return the expected number of trades needed to see a streak of exactly 3 consecutive wins for the first time.

Input:
p=0.5
Output:
14.0
With a fair coin, the expected number of flips to see 3 consecutive heads is the well-known result 2^(3+1) - 2 = 14, which matches the closed-form formula used in the general solution below.
Tap to reveal solution
Mediumsliding-windowmonotonic-dequetwo-pointer

Longest Consolidation Window (Bounded Price Range)

Given daily closing prices and a range threshold band, find the length of the longest contiguous run of days during which the price stayed within a band of width band -- i.e. max(window) - min(window) <= band, a simple consolidation / range-bound detector. Do it in O(n), not O(n^2) or O(n log n).

Input:
prices=[10,10.5,10.2,9.8,10.1,15,15.3,15.1], band=1.0
Output:
5
Days 0-4 ([10,10.5,10.2,9.8,10.1]) have range 0.7 <= 1.0, length 5. The later run [15,15.3,15.1] has range 0.3 but length only 3.
Tap to reveal solution
Mediumheapstreamingdesign

Running Median of Streaming Trade Sizes

Design a class TradeSizeMedian that supports add(trade_size), inserting a new trade size, and median(), returning the median of all trade sizes seen so far (average of the two middle values if the count is even).

Input:
add(5); median(); add(15); median(); add(1); median(); add(3); median()
Output:
5, 10.0, 5, 4.0
After [5]: median 5. After [5,15]: median (5+15)/2=10.0. After [1,5,15]: sorted [1,5,15], median 5. After [1,3,5,15]: sorted, median (3+5)/2=4.0.
Tap to reveal solution
Mediumheapdesignstreaming

Running Median of the Bid-Ask Spread From a Streaming Quote Feed

You receive a stream of quotes, each a (bid, ask) pair. After each new quote, return the running median of the spread (ask - bid) over every quote seen so far. Implement add(bid, ask) to be called once per quote, returning the updated median in O(log n) time.

Input:
add(100.00, 100.05); add(100.02, 100.09); add(99.98, 100.03)
Output:
0.05, 0.06, 0.05
Spreads in order: 0.05, 0.07, 0.05. Median after 1 value: 0.05. Median after 2 values: (0.05+0.07)/2 = 0.06. Median after 3 values, sorted [0.05, 0.05, 0.07]: 0.05.
Tap to reveal solution
Mediumheap

K Most Frequently Traded Tickers

Given a list of trade records where each record is a ticker symbol, and an integer k, return the k tickers that appear most frequently, ordered from most to least frequent. Break ties by lexicographically smaller ticker first.

Input:
trades = ["AAPL","MSFT","AAPL","GOOG","MSFT","AAPL"], k = 2
Output:
["AAPL","MSFT"]
AAPL appears 3 times, MSFT appears 2 times, GOOG appears 1 time -- the 2 most frequent are AAPL then MSFT.
Tap to reveal solution
Harddynamic-programming#309

Max Profit With a One-Day Cooldown After Selling

Given a daily price array, you may buy and sell unlimited times, holding at most one share at a time, but after selling you must wait one full day before buying again (a one-day cooldown, modeling a compliance-style restriction). Return the maximum achievable profit.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown, buy at 0, sell at 2 (profit 2), for a total of 3. Buying at 1 and selling at 3 instead leaves no time to re-enter profitably before the array ends.
Tap to reveal solution
Harddynamic-programming

Max Profit With a Cooldown Day AND a Cap of At Most K Trades

Given daily prices, an integer K capping the number of round-trip trades, and a rule that after selling you must wait one full day before buying again (cooldown), find the maximum achievable profit, holding at most one share at a time.

Input:
prices=[1,2,3,0,2], k=2
Output:
3
Buy at 1, sell at 2 (profit 1, day-of-price-3 becomes the cooldown day), then buy at 0, sell at 2 (profit 2). Two round trips totalling profit 3, respecting the one-day cooldown after each sell; no combination using at most 2 round trips beats it.
Tap to reveal solution
Mediumgreedytwo-pointer

Minimum Number of Order Batches to Keep Each Batch Under a Notional Cap

You must submit a sequence of child order notionals to the exchange in a fixed given order -- you cannot reorder them -- by grouping consecutive orders into batches. Each batch's total notional must not exceed a risk cap C. Return the minimum number of batches needed. Every individual order's notional is itself <= C.

Input:
notionals=[80,50,30,90,20], cap=150
Output:
2
Batch 1 greedily fills with 80+50=130 (adding 30 would push it to 160 > 150, so it stops there). Batch 2 takes 30+90+20=140, which fits. Two batches is also provably minimal, since the full sum 270 exceeds the 150 cap so one batch is impossible.
Tap to reveal solution
Harddynamic-programming#123

Max Profit From At Most Two Transactions With a Flat Fee Per Trade

Given a daily price array and a flat fee charged once per completed (buy, sell) pair, choose at most two non-overlapping transactions to maximize total profit after fees.

Input:
prices = [1,5,3,8], fee = 1
Output:
7
Buy at 1, sell at 5 (profit 4, minus 1 fee = 3), then buy at 3, sell at 8 (profit 5, minus 1 fee = 4). Total: 3 + 4 = 7, the best achievable with at most two trades.
Tap to reveal solution
Hardprobabilitydynamic-programming

Expected Number of Ticks to Hit a Profit Target or Stop-Loss

A position's P&L moves up by 1 tick with probability p or down by 1 tick with probability (1-p) at each step, starting at 0. Given a stop-loss at -S ticks and a take-profit at +T ticks, return the expected number of steps until the P&L is absorbed at either barrier, as a float.

Input:
p = 0.5, stop_loss = 3, take_profit = 5
Output:
15.0
For a fair (p = 0.5) random walk, the expected number of steps until absorption at either barrier is simply stop_loss * take_profit = 3 * 5 = 15.
Tap to reveal solution
Mediumheap

K Closest Trades to a Benchmark Price (Heap)

Given an array of n trade prices from a day's tape and a benchmark reference price (say, the day's VWAP), return the k trade prices closest to the benchmark, in any order. Closeness is measured by absolute difference.

Input:
prices=[8,2,14,5,11,9], benchmark=10, k=3
Output:
[8,9,11] (in some order)
Distances from 10 are 2,8,4,5,1,1. The three smallest belong to 11 (dist 1), 9 (dist 1), and 8 (dist 2), so those three prices are returned.
Tap to reveal solution
Harddesignheaphash-map

Design a Level-2 (Price-Aggregated) Order Book

Design a simplified level-2 order book for one instrument supporting add_order(side, price, qty) to add resting quantity at a price level, cancel_order(side, price, qty) to remove quantity from a level, and best_bid_ask() returning the current best (highest) bid price and best (lowest) ask price, even as price levels empty out over time.

Input:
add_order("buy",100.0,50); add_order("buy",99.5,30); add_order("sell",100.5,20); best_bid_ask(); cancel_order("buy",100.0,50); best_bid_ask()
Output:
(100.0, 100.5) then (99.5, 100.5)
After the initial orders, best bid is 100.0 and best ask is 100.5. Cancelling all 50 units at 100.0 empties that level, so the next best_bid_ask() call must skip the now-empty 100.0 level and correctly report 99.5.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Longest Contiguous Order Sequence Within a Notional Budget

Given an array of order notionals (positive integers) representing a sequence of orders arriving in time, and a capital budget, return the length of the longest contiguous run of orders whose notionals sum to at most budget.

Input:
notionals=[4,2,1,3,5], budget=6
Output:
3
The window [2,1,3] sums to 6, which is within budget, and has length 3. No length-4 window fits: [4,2,1,3] sums to 10, and [2,1,3,5] sums to 11.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit With a Mandatory Cooldown After Selling

Given daily prices for a single stock, you may buy and sell multiple times (never holding more than one share at once), but after selling you must wait one full day before you're allowed to buy again (a one-day cooldown, modeling a compliance-driven flatten-before-re-entry rule). Return the maximum total profit achievable.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown on the next day, buy at 0, sell at 2 (profit 2). Total profit 3 -- better than buying at 1 and selling at 3 for profit 2 alone, because re-entering after the dip is worth the cooldown cost.
Tap to reveal solution
Mediumprobabilityrandom-walk

Probability a Market Maker's Inventory Hits the Upper Risk Limit First

A market maker's inventory moves by +1 with probability p (a buy fill) or -1 with probability 1-p (a sell fill) with each incoming order, independent of history. Risk limits force the desk to stop and de-risk once inventory hits either 0 or N. Starting from an inventory of i (0 < i < N), compute the probability that inventory hits N before it hits 0.

Input:
N=10, i=4, p=0.5
Output:
0.4
With a symmetric walk (p=0.5) the hitting probability is exactly the linear fraction of the way from 0 to N, i/N = 4/10 = 0.4, the classic gambler's ruin result for a fair walk.
Tap to reveal solution
Mediumheapgreedy

Minimum Number of Execution Venues to Clear Non-Overlapping Block Orders

Given a list of block orders, each with a [start, end] execution time window, each venue can only work on one order at a time and an order must run start-to-end on a single venue without interruption. Return the minimum number of venues needed so every order gets executed.

Input:
orders = [[0, 30], [5, 10], [15, 20]]
Output:
2
[5, 10] and [15, 20] don't overlap each other, so they can share one venue back to back. [0, 30] overlaps both of them, so it needs a second venue.
Tap to reveal solution
Mediumheap

K Closest Trades to the Mid-Price

Given an array of trade prices executed during one second and the current mid-price, return the k trade prices closest to the mid-price. If two prices are equally close, the smaller price comes first in the result order.

Input:
prices = [101, 99, 100, 103, 97], mid = 100, k = 3
Output:
[100, 99, 101]
Distances are 1,1,0,3,3. The three closest are 100 (distance 0), then the distance-1 tie between 99 and 101, with 99 ordered first since it's the smaller price.
Tap to reveal solution
Harddynamic-programming

Max Profit With a Flat Per-Trade Fee and a Hard Cap on Total Shares Traded

Given daily prices for one instrument, a flat fee charged per round trip, and a hard budget on the TOTAL number of shares you may buy across the whole period (you trade exactly one share per transaction), choose which days to buy and sell on to maximize profit without exceeding the share budget.

Input:
prices = [3, 1, 4, 8, 2, 9], fee = 1, budget = 2
Output:
10
Buy at 1 (day 1), sell at 8 (day 3): profit 7 - 1 fee = 6, using 1 of the 2 share budget. Buy at 2 (day 4), sell at 9 (day 5): profit 7 - 1 fee = 6... but that would use both shares for a total of 12 minus 2 fees = 10. Buying at 1 and selling at 9 directly uses only 1 share for profit 8 - 1 = 7, worse than using both allowed round trips.
Tap to reveal solution
Mediumdynamic-programminggreedy#714

Best Time to Buy and Sell with Transaction Fee

Pay a fee for every completed transaction. Maximize profit net of fees.

Input:
prices = [1,3,2,8,4,9], fee = 2
Output:
8
Buy 1 sell 8 (-2 fee), buy 4 sell 9 (-2 fee) = 5 + 3 = 8.
Tap to reveal solution
Hardprobabilitymarkov-chaindynamic-programming

Expected Days Until Margin Call (Markov Chain Absorption)

An account's margin cushion is one of integer states 0..N, where state 0 means a margin call has been triggered (absorbing) and state N means fully collateralized (also absorbing, since the account tops back up to N and resets from there). From any interior state i, each day the cushion moves to i-1 with probability p, to i+1 with probability q, and stays at i with probability 1-p-q. Given a starting state s (0 < s < N), return the expected number of days until the account is either margin-called (state 0) or fully tops up (state N).

Input:
N=4, s=2, p=0.5, q=0.3
Output:
4.7059
With p=0.5, q=0.3, staying-put probability 0.2, starting at state 2 of 4, solving the linear system below for expected absorption time gives about 4.7059 days -- there is no simple closed form to recite here, it comes from solving the recurrence.
Tap to reveal solution
Mediumheap

Kth Largest Trade Size in a Streaming Feed

Given a stream of trade sizes processed one at a time, after each new trade return the current kth largest trade size seen so far (across the whole stream up to and including that trade). Return -1 for any prefix shorter than k trades.

Input:
sizes = [5,2,9,1,7], k = 2
Output:
[-1,2,5,5,7]
After the 2nd trade, the 2nd largest of {5,2} is 2. After the 3rd, the 2nd largest of {5,2,9} is 5. After the 4th, the 2nd largest of {5,2,9,1} is still 5. After the 5th, the 2nd largest of {5,2,9,1,7} is 7.
Tap to reveal solution
Hardheapsliding-windowdesign

Sliding Window Median of Trade Sizes

Given a chronological stream of trade sizes and a window length k, return the median trade size for every window of k consecutive trades, without re-sorting each window from scratch.

Input:
sizes=[100,200,50,300,250,180,400], k=3
Output:
[100, 200, 250, 250, 250]
Window [100,200,50] sorted is [50,100,200], median 100. Window [200,50,300] sorted is [50,200,300], median 200. Each subsequent window's median is found the same way, sliding one trade at a time.
Tap to reveal solution
Mediumtwo-pointersgreedy

Maximum Fillable Notional Between Two Price Levels (Container With Most Water variant)

An order book snapshot gives you the available resting size at n discrete price levels (indexed by level, not by actual price). Choose two distinct levels i and j to represent a synthetic buy-low-sell-high pair, where the notional captured between them is min(size[i], size[j]) * (j - i) -- the smaller of the two sizes (the binding constraint) times the distance between the levels. Find the maximum notional capturable over any pair of levels.

Input:
sizes = [1,8,6,2,5,4,8,3,7]
Output:
49
Levels at index 1 (size 8) and index 8 (size 7) give min(8,7) * (8-1) = 7*7 = 49, which is the maximum over all pairs.
Tap to reveal solution
Harddesignheapqueue

Design a Price-Time Priority Limit Order Matching Engine

Design a class implementing a single-instrument limit order book with price-time priority matching. add_order(order_id, side, price, qty) inserts a new limit order and immediately matches it against the opposite side's best-priced resting orders (a buy matches asks priced at or below its price, a sell matches bids priced at or above its price), with the oldest order at a given price level filling first; any unfilled remainder rests in the book. cancel(order_id) removes a resting order. best_bid() and best_ask() return the best available price on each side, or None if that side is empty.

Input:
add_order(1,'sell',101,50); add_order(2,'buy',102,30)
Output:
best_ask() -> 101; best_bid() -> None
Order 2's buy at 102 crosses order 1's ask at 101, filling 30 of order 1's 50 shares. Order 1 rests with 20 remaining at 101 (still the best ask). Order 2 is fully filled, so nothing rests on the bid side.
Tap to reveal solution
Hardheapdesign

Running Median of a Streaming Trade-Price Tape

Design a class that ingests trade prices one at a time via add_price(price) and can report the median of all prices seen so far via get_median() at any point, in better than O(n log n) per call.

Input:
add_price(5); add_price(2); get_median(); add_price(8); get_median()
Output:
3.5, 5.0
After [5,2] the sorted order is [2,5], median is the average of both middle elements, 3.5. After [5,2,8] the sorted order is [2,5,8], median is the single middle element, 5.0.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Longest Order-Flow Window With At Most K Rejects

Given a sequence of order outcomes for a session, encoded as 0 (accepted) or 1 (rejected by a pre-trade risk check), and an integer k, find the length of the longest contiguous stretch of orders containing at most k rejects.

Input:
outcomes=[0,0,1,0,1,0,0,1], k=1
Output:
4
The window [0,1,0,0] (indices 3-6) contains exactly one reject and has length 4; no window containing at most one reject is longer.
Tap to reveal solution
Harddynamic-programming

Max Profit Trading With a Configurable N-Day Cooldown

Generalize the classic 'buy/sell stock with cooldown' problem: after selling a share, you must wait `cooldown` full days before you're allowed to buy again (cooldown=1 reproduces the classic version). You may hold at most one share at a time. Given a list of daily prices and a cooldown length, return the maximum achievable profit.

Input:
prices=[1,2,3,0,2], cooldown=1
Output:
3
Buy day 0 (price 1), sell day 1 (price 2, profit 1); cooldown of 1 day means day 2 is blocked, buy day 3 (price 0), sell day 4 (price 2, profit 2). Total 1 + 2 = 3.
Input:
prices=[1,2,3,0,2], cooldown=2
Output:
2
With a stricter 2-day cooldown, selling on day 1 blocks buying until day 4 -- too late to sell again within the array. The best achievable is a single trade: buy day 0, sell day 2, for a profit of 2.
Tap to reveal solution
Mediumheap

Sliding-Window Median of Trade Prices

Given an array of trade prices and a window size k, return an array containing the median price of every contiguous window of length k as the window slides from the start of the array to the end, one trade at a time. For an even-sized window, the median is the average of the two middle values.

Input:
prices = [2, 4, 1, 7, 5, 3, 6, 8], k = 3
Output:
[2, 4, 5, 5, 5, 6]
Windows are [2,4,1]->median 2, [4,1,7]->median 4, [1,7,5]->median 5, [7,5,3]->median 5, [5,3,6]->median 5, [3,6,8]->median 6.
Tap to reveal solution
Mediumdesignstreamingmath

Design a Sliding-Window Realized Volatility Tracker

Design a class that ingests a stream of daily returns via add(ret) and supports vol(), returning the realized volatility (standard deviation) of the most recent window returns, where window is fixed at construction. Both operations must run in O(1) time; older returns are dropped once the window is full.

Input:
window=3; add(0.01); add(-0.02); add(0.015); vol(); add(0.03); vol()
Output:
first vol() = std of [0.01, -0.02, 0.015]; second vol() = std of [-0.02, 0.015, 0.03], with 0.01 evicted
Tap to reveal solution
Mediumdynamic-programmingstate-machine

Maximum Profit With Unlimited Trades and a One-Day Cooldown

Given daily prices for one instrument, you may buy and sell as many times as you like (never holding more than one unit at a time), but after selling you must wait one full day before buying again. Return the maximum total profit achievable.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown on day index 2, buy at 0, sell at 2 (profit 2): total 3. Selling at 3 first looks tempting but the mandatory cooldown after any sell forces missing the 0->2 leg entirely.
Tap to reveal solution
Mediumdesignhash-table

Design an Average-Cost Position Tracker with Realized P&L

Design a class tracking a trader's position in a single instrument using average-cost accounting. buy(qty, price) adds shares and updates the running average cost basis. sell(qty, price) reduces the position and realizes P&L as (sell_price - current_avg_cost) * qty, without changing the average cost of the shares that remain. avg_cost() returns the current average cost basis, and realized_pnl() returns cumulative realized P&L. Selling more than the current position should raise, since going short is out of scope.

Input:
buy(100,10.0); buy(100,12.0); sell(50,15.0)
Output:
avg_cost() -> 11.0, realized_pnl() -> 200.0, shares -> 150
The two buys blend to an average cost of (100*10+100*12)/200=11.0. Selling 50 shares at 15.0 realizes (15-11)*50=200 against that blended cost, and the average cost of the 150 remaining shares stays 11.0.
Tap to reveal solution
Mediumsliding-window

Longest Window of Consecutive Trades Whose Total Notional Stays Within a Risk Limit

Given an array of trade notional values (all positive) in execution order and a risk limit, return the length of the longest contiguous run of trades whose total notional never exceeds the limit.

Input:
notionals = [20,30,10,40,15], limit = 60
Output:
3
The window [20,30,10] sums to exactly 60 -- the longest run of consecutive trades that stays within the limit.
Tap to reveal solution
Hardheapsliding-windowdesign

Rolling Median Mid-Price Over a Sliding Window

Given a stream of mid-prices and a window size k, return an array of the median mid-price over each trailing window of k ticks (starting once the window first fills).

Input:
prices=[5,2,8,4,9,1], k=3
Output:
[5.0, 4.0, 8.0, 4.0]
Window [5,2,8] sorted [2,5,8] -> median 5. Window [2,8,4] sorted [2,4,8] -> median 4. Window [8,4,9] sorted [4,8,9] -> median 8. Window [4,9,1] sorted [1,4,9] -> median 4.
Tap to reveal solution
Mediumheapdesign

Top K Names by Absolute Factor Exposure, Streaming Daily

You receive a daily stream of (ticker, factor_exposure) updates -- each update replaces that ticker's current exposure (tickers can repeat across days). After each update, report the K tickers with the largest absolute factor exposure, in descending order of |exposure|.

Input:
k=2; updates=[('AAPL',0.8),('MSFT',-1.2),('GOOG',0.5),('AAPL',-2.0)]
Output:
[['AAPL'], ['MSFT','AAPL'], ['MSFT','AAPL'], ['AAPL','MSFT']]
After update 4, AAPL's exposure was overwritten from 0.8 to -2.0, so |AAPL| becomes the largest, ahead of MSFT's |-1.2|.
Tap to reveal solution
Mediumdynamic-programming

Max Profit From Unlimited Round Trips With a Flat Fee Per Trade

Given daily prices for one instrument and a flat fee charged per round-trip trade (deducted once, whenever you sell), you may buy and sell as many times as you like, but must be flat before buying again. Return the max total profit.

Input:
prices = [1,3,2,8,4,9], fee = 2
Output:
8
Buy at 1, sell at 8 (profit 7, minus 2 fee = 5). Buy at 4, sell at 9 (profit 5, minus 2 fee = 3). Total 5 + 3 = 8. Trading more often adds fees without enough extra profit to clear them.
Tap to reveal solution
Mediumdesignqueue

Design a Sliding-Time-Window VWAP Calculator

Design a class that ingests trades as they arrive, each with a strictly increasing timestamp, a price, and a size, and supports get_vwap(), returning the volume-weighted average price (sum of price times size, divided by sum of size) over only the trades within the trailing window_seconds seconds of the most recent trade.

Input:
window_seconds=60; add_trade(t=0,price=100,size=10); add_trade(t=30,price=102,size=5); add_trade(t=70,price=105,size=20); get_vwap()
Output:
104.4
The trade at t=0 falls outside the trailing 60-second window once the trade at t=70 arrives (70-60=10, and 0<=10), so only the t=30 and t=70 trades remain: (102*5+105*20)/(5+20) = 2610/25 = 104.4.
Tap to reveal solution
Harddesignheap

Design a Limit Order Book Matching Engine With Price-Time Priority

Design a class OrderBook supporting add_limit_order(side, price, qty), which adds a buy or sell limit order and immediately matches it against the opposite side's resting orders by price-time priority (best price first; among equal prices, earliest arrival first) for as much quantity as the price allows, resting any unfilled remainder in the book. It returns the list of (price, qty) fills generated by that call. Also support best_bid() and best_ask(), each returning the current best resting price on its side, or None if that side is empty.

Input:
add_limit_order("sell", 101, 50); add_limit_order("sell", 100, 30); add_limit_order("buy", 100, 40); best_bid(); best_ask()
Output:
fills of the third call: [(100, 30)]; best_bid() = 100; best_ask() = 101
The incoming buy at 100 can only cross asks priced at or below 100, so it matches the resting 100 x 30 ask in full (a fill of 30 at 100) but cannot touch the 101 x 50 ask, which is priced above what the buyer is willing to pay. The remaining 10 units of the buy order rest in the book at 100, becoming the new best bid; the untouched 101 x 50 sell remains the best ask.
Tap to reveal solution
Harddynamic-programming

Max Profit With a Cooldown and a Per-Day Short-Borrow Fee

Given daily prices for a stock, you may hold a single-unit LONG or SHORT position (never both at once), must wait one day after closing any position before opening a new one (cooldown), and pay a fixed per-day borrow fee for every day a SHORT position remains open, charged on both the day it opens and every day it is held. Return the maximum achievable profit, ending flat.

Input:
prices=[10,15,12,20], fee=1
Output:
10
Buying at 10 (day 0) and selling at 20 (day 3) nets 10. The DP also explores opening and holding shorts along the way, but none of those round trips close out more profitably within this short window.
Tap to reveal solution
Mediumstackmonotonic-stackdesign#901

Online Stock Span (Monotonic Stack)

Design a class that takes daily stock prices in arrival order and, for each new price, returns the 'span' — the number of consecutive days (including today) where the price was <= today's price.

Input:
prices stream: 100, 80, 60, 70, 60, 75, 85
Output:
1, 1, 1, 2, 1, 4, 6
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most Two Round-Trip Transactions

Given daily prices for one stock, find the maximum profit achievable using at most two non-overlapping buy-then-sell round trips (you must sell before you can buy again).

Input:
prices=[3,3,5,0,0,3,1,4]
Output:
6
Buy at 0 (day 3), sell at 3 (day 5) for a profit of 3, then buy at 1 (day 6), sell at 4 (day 7) for a profit of 3 -- two disjoint round trips totalling 6, more than any single round trip achieves on its own.
Tap to reveal solution
Mediumheap

Merge K Sorted Venue Price Ladders Into One Combined Ladder

You receive ask-side price ladders from k different venues, each already sorted ascending by price (duplicates across venues are kept -- each entry represents separate liquidity). Merge all k ladders into one fully sorted combined ladder.

Input:
ladders = [[100.0,101.5,103.0],[100.5,102.0],[99.5,100.0,104.0]]
Output:
[99.5,100.0,100.0,100.5,101.5,102.0,103.0,104.0]
All 8 price levels across the 3 venues, merged into one ascending sequence. The two 100.0 entries come from different venues and both survive.
Tap to reveal solution
Mediumdynamic-programming#198

Maximum P&L With a One-Day Compliance Blackout After Every Trade

Given daily P&L opportunities pnl[i] (the profit available if you trade on day i, which can be negative), you may trade on any subset of days, but compliance forbids trading on two consecutive days -- trading on day i mandates a blackout on day i+1. Return the maximum total P&L achievable.

Input:
pnl=[3,-2,5,10,-1,4]
Output:
17
Trade on days 0, 3, and 5 (profits 3, 10, and 4) for a total of 17. None of those days are consecutive, so no blackout is violated, and skipping the negative-pnl days 1 and 4 entirely avoids both a loss and an unnecessary blackout.
Tap to reveal solution
Hardprobabilitymarkov-chain

Probability of Hitting a Profit Target Before a Loss Limit

A trader's PnL moves in discrete $1 steps: up with probability p, down with probability 1-p, independently each step. Starting from a current PnL of i (with 0 < i < N), the trader stops the first time PnL hits either the loss limit 0 or the profit target N. Return the probability of hitting the profit target N before the loss limit 0.

Input:
p=0.5, i=3, N=10
Output:
0.3
For a fair (p=0.5) random walk, the ruin-probability closed form degenerates to the simple linear case: probability of reaching N first is i/N = 3/10 = 0.3.
Tap to reveal solution
Harddynamic-programming

Maximum Profit with At Most K Trades

Given a name's daily closing prices over n days and an integer k, find the maximum profit achievable using at most k buy-then-sell transactions, where you must sell (and the position must be flat) before buying again, and you can hold at most one unit of position at a time.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 (profit 4), then buy at 0, sell at 3 (profit 3), for a total of 7 using exactly 2 of the allowed 2 transactions -- no combination of at most 2 trades beats this.
Tap to reveal solution
Mediumheap#973

K Closest Executed Trade Prices to a Reference Price

Given an array of this session's executed trade prices and a reference price (e.g. a theoretical fair value), return the k trade prices closest to the reference, in any order.

Input:
prices = [186.40, 187.10, 185.90, 188.00, 187.05], ref = 187.00, k = 3
Output:
[186.40, 187.05, 187.10]
Distances from 187.00 are 0.60, 0.10, 1.10, 1.00, 0.05 -- the three smallest belong to 187.05, 187.10, and 186.40.
Tap to reveal solution
Mediumdynamic-programming#309

Maximum Profit With a Mandatory One-Day Settlement Cooldown After Selling

Given a sequence of daily prices, you may buy and sell an unlimited number of times (never holding more than one share at once), but after selling you must wait one full day before buying again -- a T+1 settlement cooldown. Return the maximum achievable profit.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy day0 @1, sell day1 @2 (profit 1), cooldown on day2, buy day3 @0, sell day4 @2 (profit 2). Total profit 1 + 2 = 3.
Tap to reveal solution
Hardheap#295

Streaming Median of Fill Sizes From a Live Execution Feed

Design a class that consumes a live stream of trade fill sizes one at a time via add_fill(size) and supports current_median() at any point, returning the median of all fills seen so far.

Input:
add_fill(200); add_fill(500); current_median(); add_fill(100); current_median()
Output:
350.0, 200.0
After [200, 500] the median of the two middle values is (200+500)/2 = 350.0. After adding 100, the sorted fills are [100, 200, 500] and the median is the middle value, 200.0.
Tap to reveal solution
Harddynamic-programming

Maximum Profit with a Mandatory Minimum Holding Period

Given daily closing prices and an integer d, find the maximum profit from any number of buy-then-sell transactions, holding at most one unit at a time, where a compliance rule requires holding each position for at least d days before selling -- sell day minus buy day must be >= d. You may re-buy immediately after selling, with no cooldown beyond the holding-period rule.

Input:
prices=[1,4,2,8,5], d=2
Output:
7
Buy on day 1 at price 1 and sell on day 4 at price 8 -- a 3-day hold, satisfying d=2 -- for a profit of 7. No combination of shorter, disjoint transactions that respects the minimum hold beats this single trade.
Tap to reveal solution
Mediumheap#23

Merge K Sorted Venue Tick Streams Into One Global Tape

You receive trade prints from k different venues, each already sorted by timestamp within its own feed, as k separate lists. Merge all k lists into a single list sorted by timestamp, reconstructing the one true consolidated tape a smart order router would have seen.

Input:
streams = [[(1, 'A'), (5, 'A')], [(2, 'B'), (3, 'B')], [(4, 'C')]]
Output:
[(1,'A'), (2,'B'), (3,'B'), (4,'C'), (5,'A')]
Each inner list is already sorted by its own timestamp; the merged tape just needs all k lists interleaved by timestamp across venues.
Tap to reveal solution
Easydynamic-programminggreedy

Best Single Trade Profit Allowing Either a Long or a Short Position

Given daily prices for a stock, you may make exactly one round-trip trade: either go long (buy then sell later at a higher price) or go short (sell then buy back later at a lower price) -- whichever direction produces the larger single-trade profit. Return the maximum achievable profit, or 0 if no profitable trade exists in either direction.

Input:
prices=[7,1,5,3,6,4]
Output:
6
Shorting at 7 (day 0) and covering at 1 (day 1) profits 6, which beats the best long trade of 5 (buy at 1, sell at 6).
Tap to reveal solution
Harddesign

Design a Price-Level Aggregated Level 2 Order Book

Design an order book supporting add_order(side, price, size) (side is 'bid' or 'ask'), cancel_order(order_id), and best_bid() / best_ask(), where best_bid/best_ask return the highest bid price / lowest ask price that still has positive total resting size. Orders at the same price level aggregate.

Input:
add_order('bid', 100, 10, id=1); add_order('bid', 101, 5, id=2); cancel_order(2); best_bid()
Output:
100
After adding bids at 100 and 101 and then cancelling the order at 101, only the level at 100 still has resting size, so best_bid() returns 100.
Tap to reveal solution
Easysliding-windowtwo-pointer

Longest Trading Window With At Most K Circuit-Breaker Halts

Given a binary array where a 1 marks a minute in which trading was halted by a circuit breaker and 0 marks a normal trading minute, find the length of the longest contiguous window of minutes containing at most k halted minutes.

Input:
halts=[0,0,1,0,0,1,1,0], k=1
Output:
5
The window [0,0,1,0,0] (indices 0-4) contains exactly 1 halt and has length 5; every length-6 window in this array contains 2 or more halts.
Tap to reveal solution
Harddesignheap

Design a Market-Data Sequence-Gap Detector With an Out-of-Order Replay Buffer

A UDP market-data feed delivers packets tagged with a per-symbol sequence number that increases by exactly 1 each packet, but packets can arrive out of order or be dropped and retransmitted later out of band. Design a class SequenceGapBuffer with push(seq, payload), which returns, in strict order, every contiguous run of payloads that is now ready to emit (seq equals the next expected sequence number), buffering anything that arrives early until its predecessors show up, and silently discarding anything that arrives late (already emitted).

Input:
buf=SequenceGapBuffer(start_seq=1); buf.push(1,'A'); buf.push(3,'C'); buf.push(2,'B'); buf.push(4,'D')
Output:
['A'], [], ['B','C'], ['D']
Packet 1 arrives in order and is emitted immediately. Packet 3 arrives early (2 is still missing), so it's held with nothing emitted. Packet 2 then fills the gap, so it's emitted AND immediately drains the now-contiguous packet 3 behind it, in one call. Packet 4 arrives in order and is emitted on its own.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Longest Window Whose Realized Variance Stays Under a Budget

Given a sequence of daily returns and a variance budget V, find the length of the longest contiguous window whose sum of squared returns (a proxy for realized variance over the window) does not exceed V.

Input:
returns=[0.1, 0.1, 0.1, 0.1], V=0.03
Output:
3
Each squared return is 0.01. Any 3 consecutive days sum to 0.03, right at the budget, which is allowed; any 4 consecutive days sum to 0.04, over budget. The longest valid window has length 3.
Tap to reveal solution
Mediumprobabilitydynamic-programming

Probability of Hitting a Profit Target Before a Stop-Out

A trader starts with i units of risk capital. Each independent trade wins +1 unit with probability p or loses -1 unit with probability 1-p. Trading stops the moment capital hits 0 (stopped out) or hits a target N (profit target reached). Given i, N, and p, compute the probability the trader reaches the target before being stopped out.

Input:
i=4, N=10, p=0.5
Output:
0.4
With fair odds (p=0.5), the classic gambler's ruin result reduces to the linear i/N = 4/10 = 0.4 -- capital position alone determines the odds when there's no edge either way.
Tap to reveal solution
Mediumdesignqueue

Design an Iceberg Order Matching Engine

Design a single-price-level book that supports add(order_id, side, price, total_qty, display_qty), which rests an iceberg order showing only display_qty at a time while hiding the rest, and match(side, price, qty), which fills an incoming aggressor of that size against resting opposite-side iceberg orders at that price using price-time priority. When a resting order's visible slice is fully consumed, immediately replenish it from its hidden quantity and move it to the back of the time-priority queue at that price (it loses priority, matching how real iceberg orders behave). Return the list of (order_id, price, qty) fills produced, in the order they occurred.

Input:
add('I1','sell',100,300,100); match('buy',100,150)
Output:
[('I1', 100, 100), ('I1', 100, 50)]
I1 rests 300 total shares showing 100 at a time. The incoming buy for 150 first consumes the full 100-share visible slice, which triggers a replenish from the 200 hidden shares (new visible slice of 100), then consumes 50 more from the replenished slice -- two separate fill events against the same order because the slice ran out mid-match.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Longest Trading Window With Cumulative Volume Under a Cap

Given an array of per-minute trade volumes and a maximum volume cap, return the length of the longest contiguous window of minutes whose total volume does not exceed the cap.

Input:
volumes=[100, 50, 100, 50, 100], cap=250
Output:
3
The window [100, 50, 100] (indices 2-4) sums to 250, exactly at the cap, and is the longest such window.
Tap to reveal solution
Easyheapdesign#703

Kth Largest Element in a Stream

Design a class that returns the k-th largest element of the stream after each insertion.

Input:
k=3, init [4,5,8,2], add 3 -> ?, add 5 -> ?
Output:
4, 5
Tap to reveal solution
Mediumheaphash-map

Maintain the Top-K Highest-Volume Tickers Across a Stream of Trade Updates

You receive a stream of trade updates, each (ticker, volume_traded), where the same ticker can appear multiple times and its cumulative volume keeps growing. After each update, you need to be able to report the current top-K tickers by cumulative volume. Design update(ticker, volume_traded) and get_top_k() methods.

Input:
k=2; update('AAPL',100); update('MSFT',50); update('AAPL',80); get_top_k()
Output:
['AAPL','MSFT']
AAPL's cumulative volume is 180, MSFT's is 50 -- both are in the top 2 trivially since there are only 2 tickers seen so far.
Tap to reveal solution
Hardheapdesignhash-map

Design a Live Top-K Sharpe Ratio Leaderboard

Design a leaderboard that tracks a live Sharpe ratio for each of many trading strategies. It must support update(strategy_id, sharpe), which sets or resets a strategy's current Sharpe ratio, and top_k(k), which returns the k strategies with the highest current Sharpe ratio, best first. A strategy's Sharpe changes frequently as new data arrives, and the leaderboard must stay efficient across many updates and queries, not just a handful.

Input:
update('A', 1.5); update('B', 2.1); update('C', 0.8); top_k(2)
Output:
['B', 'A']
B has the highest current Sharpe (2.1), followed by A (1.5); C (0.8) doesn't make the top 2.
Input:
update('A', 3.0); top_k(1)
Output:
['A']
A's Sharpe was just updated to 3.0, overtaking B -- the leaderboard reflects the latest value per strategy, not every historical update.
Tap to reveal solution
Mediumdesignmulti-armed-bandit

Design an Epsilon-Greedy Smart Order Router Across Venues

Design an order router that sends each child order to one of k execution venues and shortly after observes a binary fill outcome. Implement route(), which selects a venue to try next, and update(venue, filled), which records the outcome, so that over many orders the router increasingly favors venues with higher observed fill rates while still occasionally exploring others in case a venue's fill rate has genuinely changed.

Input:
router = EpsilonGreedyRouter(k=3, epsilon=0.1); repeated route()/update() calls
Output:
early routing is close to uniform across the 3 venues; over time it concentrates on whichever venue has the highest empirical fill rate, with roughly 10% of routes still going to a randomly chosen venue
Epsilon-greedy is the simplest working multi-armed-bandit policy: exploit the current best estimate most of the time, explore uniformly at random the rest of the time, so the estimate keeps adapting if venue fill rates drift.
Tap to reveal solution
Mediumdynamic-programming

Max Profit With Unlimited Transactions and a Flat Fee

Given daily prices for one stock and a fixed transaction fee charged once per completed round trip (a buy followed by a sell), find the maximum profit achievable from an unlimited number of transactions. You must sell your current position before buying again.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
8
Buy at 1, sell at 8 (profit 7-2=5 after fee), buy at 4, sell at 9 (profit 5-2=3 after fee) -- total 8. Taking the small 1->3 move separately nets less once each round trip pays its own fee.
Tap to reveal solution
Easydynamic-programmingfibonacci#70

Climbing Stairs

You are climbing a staircase that takes n steps to reach the top. Each time you can climb either 1 or 2 steps. How many distinct ways can you climb to the top?

Input:
n = 2
Output:
2
1+1, 2
Input:
n = 3
Output:
3
1+1+1, 1+2, 2+1
Tap to reveal solution
Mediumsliding-window

Longest Window of Trades Touching At Most K Venues

Given an array of venue codes, one per trade print in chronological order, and an integer k, return the length of the longest contiguous window of trades that touches at most k distinct venues.

Input:
venues = ["NYSE","NYSE","ARCA","NYSE","IEX","ARCA","ARCA"], k = 2
Output:
4
The window [NYSE, NYSE, ARCA, NYSE] (indices 0-3) touches only {NYSE, ARCA} -- 2 distinct venues -- and length 4. Extending it to include IEX at index 4 would push distinct venues to 3, violating k.
Tap to reveal solution
Harddesignheap

Design a Price-Time-Priority Limit Order Book

Design a single-instrument limit order book supporting add_order(order_id, side, price, quantity), which matches the incoming order against resting opposing orders using strict price-time priority (best price first, ties broken by earliest arrival), partially filling as needed and resting any unfilled remainder; and cancel(order_id), which removes a resting order. add_order returns the list of fills it produced, each as (resting_order_id, incoming_order_id, price, quantity).

Input:
add_order(1,"BUY",100,10); add_order(2,"SELL",99,4); add_order(3,"SELL",101,5)
Output:
[], [(1,2,100,4)], []
Order 1 rests as a bid at 100 (nothing to match against). Order 2 crosses (sell limit 99 <= resting bid 100) and fills 4 against order 1 at the RESTING order's price of 100, leaving order 1 with 6 left resting. Order 3's limit of 101 doesn't cross the remaining bid of 100, so it rests as a new ask.
Tap to reveal solution
Mediumarrayhash-tableprefix-sum

Shortest Contiguous Trade Run Summing to a Target Net Exposure

Given an array of signed trade sizes (positive = buy, negative = sell) in execution order, and a target net exposure, return the length of the shortest contiguous run of trades whose sizes sum exactly to the target. Return -1 if no such run exists. Trade sizes can be negative, so a two-pointer window is not directly valid.

Input:
trades=[4,1,-2,3], target=5
Output:
2
The run [4,1] sums to 5 in 2 trades. No single trade equals 5, and every other contiguous run either misses the target or is longer, so 2 is shortest.
Tap to reveal solution
Mediumheapgreedyintervals

Minimum Matching Engines to Cover Overlapping Order Lifetimes

Given the lifetime of each resting order as [submit_time, cancel_or_fill_time), find the minimum number of matching-engine slots needed so that no slot ever has to process two orders whose lifetimes overlap -- equivalently, the peak number of orders open in the book at any single instant.

Input:
intervals=[[0,5],[2,7],[4,6],[8,9]]
Output:
3
At time 4, orders [0,5], [2,7], and [4,6] are all simultaneously resting -- three engines are needed at that instant, and no time has four orders open at once.
Tap to reveal solution
Mediumprobabilitymarkov-chain

Two-State Volatility Regime: Expected Duration and Stationary Share

A volatility regime model has two states, LOW and HIGH. Each day, if the market is in LOW it switches to HIGH with probability p_lh (else stays LOW); if in HIGH it switches to LOW with probability p_hl (else stays HIGH). Given p_lh and p_hl, compute the expected number of consecutive days spent in each state before it switches away, and the long-run fraction of days spent in LOW.

Input:
p_lh=0.1, p_hl=0.25
Output:
expected_low=10.0, expected_high=4.0, pi_low=0.7143
Leaving LOW is a geometric event with success probability 0.1, so the expected sojourn is 1/0.1 = 10 days; symmetrically for HIGH. The stationary share of LOW is p_hl / (p_lh + p_hl) = 0.25 / 0.35.
Tap to reveal solution
Mediumheap

K Trade Prices Closest to a Reference Price (Bounded Max-Heap)

Given a list of executed trade prices and a reference price (e.g. the arrival price for a slippage study), return the k trade prices whose distance from the reference is smallest. Order of the output doesn't matter.

Input:
trades = [10, 2, 14, 4, 7, 6], ref = 5, k = 3
Output:
[4, 6, 7] (any order)
Distances from 5: 10->5, 2->3, 14->9, 4->1, 7->2, 6->1. The three smallest distances belong to 4 (1), 6 (1), and 7 (2).
Tap to reveal solution
Mediumdynamic-programming#309

Best Time to Buy and Sell Stock with Cooldown

Maximize profit trading a single stock with unlimited transactions, where after selling you must wait one full day of cooldown before buying again. No transaction fee.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown, buy at 0, sell at 2 (profit 2); total 3.
Tap to reveal solution
Harddesignheaporder-book

Design a Price-Time-Priority Limit Order Matching Engine

Design a single-symbol matching engine with add_order(side, price, size, order_id) for side in {'buy','sell'}. An incoming order matches against resting orders on the OPPOSITE side whenever the prices cross (incoming buy price >= a resting ask, or incoming sell price <= a resting bid), always filling against the best available price first and, among orders tied at the same price, the one that arrived earliest (FIFO). Any unfilled remainder rests on the book. Return the list of fills (resting_order_id, incoming_order_id, price, size) produced by each call.

Input:
add_order('sell',101,5,'A'); add_order('sell',101,3,'B'); add_order('buy',101,6,'C')
Output:
[('A','C',101,5), ('B','C',101,1)]
Both resting asks are at the same price 101, so FIFO breaks the tie: A (arrived first) fills completely against 5 of C's 6 units at 101, then B fills the remaining 1 unit at 101, leaving B resting with 2 units still on the book.
Tap to reveal solution
Harddynamic-programming

Max Profit With Unlimited Trades Where Every Position Must Be Held At Least M Days

Given a daily price array and an integer m, you may buy and sell an unlimited number of times, but once you buy on day i you are not allowed to sell until day i + m or later (you must hold for at least m days). Return the maximum achievable profit.

Input:
prices = [1,2,10], m = 2
Output:
9
Buy on day 0 at price 1. The earliest eligible sell day is day 0 + 2 = day 2 (price 10), since day 1 is only 1 day of holding. Selling on day 2 gives profit 10 - 1 = 9.
Tap to reveal solution
Harddesign

Design an LFU Cache for Recently-Quoted Instrument Snapshots

Design a cache with fixed capacity that stores the latest quote snapshot per instrument, supporting get(symbol) and put(symbol, quote). When the cache is full and a new symbol must be inserted, evict the LEAST FREQUENTLY accessed symbol; if there's a tie in access frequency, evict the least recently used among them. Both get and put count as an access.

Input:
capacity=2; put(A,q1); put(B,q2); get(A); put(C,q3); get(B); get(C)
Output:
q1, None, q3
get(A) bumps A's frequency above B's. Inserting C forces an eviction: A has freq 2, B has freq 1, so B (least frequent) is evicted, not A. get(B) then returns None, get(C) returns q3.
Tap to reveal solution
Mediumprobabilitymath

Probability of Hitting a Stop-Out Before a Profit Target on a Random-Walk Inventory

A market maker's inventory starts at i lots (0 < i < N) and changes by +1 or -1 each tick with equal probability 0.5 each, independent across ticks. Inventory hitting 0 means a forced stop-out (de-risking); hitting N means a profit target that closes the book. Return the probability the stop-out (0) is hit before the profit target (N).

Input:
i=2, N=5
Output:
0.6
This is the classic gambler's ruin setup with fair (p=0.5) steps. For a fair random walk, the probability of ruin starting from i is exactly (N-i)/N, so with i=2 and N=5 that's (5-2)/5 = 0.6.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With Cooldown

Given daily prices, you may hold at most one share at a time and make unlimited transactions, but after selling you must wait one full day (a cooldown) before you may buy again. Return the maximum achievable profit.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), cooldown one day, buy at 0, sell at 2 (profit 2). Total profit 1+2=3, better than any single round trip alone.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Trades Until K Consecutive Winning Trades (Signal Confirmation)

Each trade independently wins with probability p (and loses with probability 1 - p). You stop the first time you observe k winning trades in a row. Return the expected number of trades needed to reach that stopping point.

Input:
p = 0.5, k = 2
Output:
6.0
This is the classic expected-waiting-time-for-a-streak result: with a fair coin, the expected number of flips to see 2 heads in a row is 6, and the same Markov-chain structure applies here with wins in place of heads.
Tap to reveal solution
Mediumheap

Running Median of Trade Prices in a Live Tape

Design a class MedianTracker with add(price) that ingests one trade price at a time, and median() that returns the median of all prices ingested so far.

Input:
add(5); add(15); add(1); median(); add(3); median()
Output:
5, then 4.0
After [5,15,1], sorted is [1,5,15], median is the middle value 5. After adding 3, sorted is [1,3,5,15], median is the average of the two middle values (3+5)/2 = 4.0.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position Tracker With Realized P&L

Design a class PositionTracker for a single symbol supporting buy(qty, price) and sell(qty, price), which realize P&L against the OLDEST open lots first (FIFO cost basis), and net_position(), which returns the current signed share count. Selling can only be called with qty <= current long position (no shorting in this version).

Input:
buy(100, 10.0); buy(50, 12.0); sell(120, 15.0); net_position()
Output:
realized P&L = 560.0; net_position() = 30
The sell of 120 consumes the full first lot (100 @ 10) and 20 shares of the second lot (@ 12) FIFO: 120*15 - (100*10 + 20*12) = 1800 - 1240 = 560. That leaves 30 shares of the second lot still open.
Tap to reveal solution
Mediumdynamic-programming#309

Max Profit With a Mandatory One-Day Settlement Cooldown After Selling

Given a daily price array, you may buy and sell as many times as you like (one share at a time, must fully sell before buying again), but after selling you must wait one full day before buying again (a settlement cooldown). Return the maximum achievable profit.

Input:
prices = [1,2,3,0,2]
Output:
3
Buy at 1, sell at 3 for a profit of 2, rest the mandatory cooldown day (price 0), then buy at 2's... actually buy at 0 and sell at 2 for a profit of 2 is blocked by the cooldown from the first sale landing on day index 2; the best achievable sequence nets 3 total, beating any single round trip alone.
Tap to reveal solution
Easyheapsorting

K Closest Trade Prices to a Reference Price

Given a list of trade prices and a reference price target, return the k trade prices closest to target, ordered by distance ascending. Break ties between equally-close prices by preferring the lower price.

Input:
prices=[10,7,15,12,9], target=11, k=3
Output:
[10,12,9]
Distances to 11: 10->1, 12->1, 9->2, 7->4, 15->4. The three closest are 10 and 12 (tied at distance 1, lower price 10 first) then 9 (distance 2).
Tap to reveal solution
Mediumsliding-window

Longest Window Where Realized Volatility Stays Under a Threshold

Given a list of daily returns rets and a volatility cap max_vol, return the length of the longest contiguous run of days whose realized volatility (population standard deviation of the returns in that run) is at most max_vol. The window must have at least 2 days.

Input:
rets=[0.01,-0.01,0.02,-0.015,0.10,-0.08,0.01], max_vol=0.02
Output:
4
The first four days [0.01,-0.01,0.02,-0.015] have a population std of about 0.0132, under the 0.02 cap. Extending to include the 0.10 and -0.08 shock days pushes std well past the cap, so the longest qualifying run has length 4.
Tap to reveal solution
Mediumheap

K Trades Closest to the Current Mid Price

Given a stream of recent trade prices and the current mid price, return the K trade prices closest to the mid. Break ties by preferring the lower price. The result does not need to preserve the original stream order, but should be sorted by closeness (then by price) for a deterministic answer.

Input:
trades = [98, 99, 101, 102, 97], mid = 100, k = 3
Output:
[99, 101, 98]
Distances from mid: 98 -> 2, 99 -> 1, 101 -> 1, 102 -> 2, 97 -> 3. The three closest are 99 and 101 (distance 1 each), then a tie between 98 and 102 at distance 2 -- the lower price, 98, wins the tie. Sorted by (distance, price): 99, 101, 98.
Tap to reveal solution
Harddynamic-programming

Best Time to Buy and Sell Stock With At Most K Transactions

Given daily prices and an integer k, you may complete at most k buy-then-sell round trips (each must fully close before the next opens; no overlapping positions). Return the maximum achievable profit.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3). Total 4+3=7, the best split into at most 2 round trips.
Tap to reveal solution
Mediumprobabilitymath

Expected Days Until a Portfolio Doubles or Halves (Gambler's Ruin)

A portfolio starts at $i and, each day, moves up by $1 with probability p or down by $1 with probability 1-p, independently. Trading stops the moment the portfolio hits either $0 (ruin) or $N (target). Given N, i, and p=0.5, what is the expected number of days until trading stops?

Input:
N=10, i=4, p=0.5
Output:
24.0
For a fair (p=0.5) symmetric random walk between two absorbing barriers, the classic gambler's ruin formula for expected time to absorption is E[i] = i * (N - i). Plugging in gives 4 * (10 - 4) = 24.0.
Tap to reveal solution
Harddynamic-programming

Maximum Profit From At Most K Round Trips With a Per-Trade Fee

Given a single instrument's daily prices, a fixed per-transaction fee charged on every sell, and a maximum of K completed round trips (buy then later sell) allowed, with at most one open position at a time, find the maximum achievable profit.

Input:
prices=[3,2,6,5,0,3], k=2, fee=1
Output:
5
Buy at 2, sell at 6 (profit 4-1=3 after fee); buy at 0, sell at 3 (profit 3-1=2 after fee); total 5, using 2 of the allowed 2 round trips.
Tap to reveal solution
Mediumprobabilityrandom-walkmath

Probability of Ruin in a Biased Random Walk

A trader starts with i units of capital and repeatedly makes a bet that wins 1 unit with probability p and loses 1 unit with probability 1-p, stopping either at 0 (ruin) or at a target N. Given i, N, and p, compute the probability of eventually being ruined (hitting 0 before N), without simulating the walk.

Input:
i=1, N=3, p=0.4
Output:
0.771
A disadvantageous walk (p < 0.5): ruin probability is high even starting closer to the middle than to 0.
Tap to reveal solution
Harddynamic-programmingbinary-search

Maximum Profit From Non-Overlapping Trade Windows

You're given a list of candidate trade windows, each (start_time, end_time, profit), representing a position you could hold from start_time to end_time for a known profit. You may only hold one position at a time, so chosen windows can't overlap (touching at the same instant is allowed -- one can start exactly when another ends). Choose a subset of non-overlapping windows to maximize total profit.

Input:
windows=[(1,3,5),(2,5,6),(4,6,5),(6,7,4)]
Output:
14
Taking (1,3,5), (4,6,5), and (6,7,4) -- all mutually non-overlapping (touching at t=6 is fine) -- totals 5+5+4=14, which beats any other combination including the single best-looking window (2,5,6).
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position Tracker With Realized P&L

Design a class that tracks a single instrument's position using FIFO lot accounting. Implement buy(qty, price) to add a new lot, and sell(qty, price), which consumes the OLDEST open lots first and returns the realized P&L generated by the sale, computed against each consumed lot's own original cost (not a blended average). Also expose get_position(), returning the current total open quantity and its quantity-weighted average remaining cost basis. Assume a sell never exceeds the currently open quantity.

Input:
buy(100,10.0); buy(50,12.0); sell(120,15.0)
Output:
realized P&L = 560.0; get_position() = (30, 12.0)
The sell of 120 first fully consumes the oldest lot, 100 shares at cost 10.0, for a profit of (15-10)*100=500, then consumes 20 of the 50 shares from the next lot at cost 12.0, for a profit of (15-12)*20=60. Total realized 560.0, leaving 30 shares of the second lot still open at its original cost of 12.0.
Tap to reveal solution
Easydesignstate-machine

Design a Trailing-Stop Order Tracker

Design a class TrailingStop for a long position, constructed with an entry price and a trailing distance. update(price) is called once per new tick and returns the current stop level; the stop level ratchets up to (highest price seen - trail) whenever price makes a new high, and never moves down on a pullback. is_triggered(price) returns whether price has fallen to or below the current stop level.

Input:
TrailingStop(entry_price=100.0, trail=5.0); update(102.0); update(101.0); update(96.5)
Output:
stop levels: 97.0, 97.0, 97.0; is_triggered(96.5) = True
A new high of 102.0 raises the stop to 97.0. The pullback to 101.0 does NOT lower the stop back down -- it stays at 97.0. The drop to 96.5 is at or below 97.0, so the stop triggers.
Tap to reveal solution
Hardheap#480

Running Median Trade Price Over the Last K Ticks (Sliding Window Median)

Given a stream of trade prices and a window size k, return the median trade price over the last k ticks after each new tick arrives (once at least k ticks have arrived). This feeds a robust, outlier-resistant rolling fair-value estimate that a single fat-finger print can't drag around the way a rolling mean would.

Input:
prices = [5, 2, 8, 4, 9, 1], k = 3
Output:
[5.0, 4.0, 8.0, 4.0]
Window [5,2,8] has median 5.0, [2,8,4] has median 4.0, [8,4,9] has median 8.0, [4,9,1] has median 4.0 -- one output per tick once the window first fills.
Tap to reveal solution
Mediumheapdesign

Merge K Sorted Trade-Print Streams Into One Consolidated Tape

You receive trade timestamps from k different exchange feeds, each individually sorted ascending but arriving as separate streams. Merge all k streams into one fully sorted list of timestamps representing the consolidated tape.

Input:
streams=[[1,4,7],[2,3,8],[5,6]]
Output:
[1,2,3,4,5,6,7,8]
Each input stream is already sorted on its own; the merged output interleaves all three into one globally sorted sequence.
Tap to reveal solution
Mediumheap#703

Kth-Largest Trade Size Seen So Far, Updated After Every New Print

Given a stream of trade sizes (positive integers) arriving one at a time and an integer k, return, after each new trade, the k-th largest trade size among all trades seen so far, or -1 if fewer than k trades have arrived yet.

Input:
sizes = [300,100,500,200,500], k = 3
Output:
[-1,-1,100,200,300]
After 1 or 2 trades there aren't yet 3 prints, so -1. After {300,100,500} the 3rd largest is 100. After {300,100,500,200} the 3rd largest is 200. After {300,100,500,200,500} the 3rd largest is 300.
Tap to reveal solution
Mediumheapdesign

Kth Largest Trade Size in a Live Stream

Design a class that ingests a live stream of trade sizes one at a time via add(size), and after each addition returns the Kth largest trade size seen so far (K is fixed at construction). Assume at least K trades have already arrived before the first query that matters.

Input:
k=3; add(50) -> 50; add(200) -> None; add(120) -> 50; add(80) -> 80; add(300) -> 120
Output:
the running 3rd-largest after each add
After [50,200,120] the 3rd largest of {50,120,200} is 50. After adding 80, {80,120,200} makes the 3rd largest 80. After adding 300, {120,200,300} makes it 120.
Tap to reveal solution
Mediumprobabilitydynamic-programming

N-Step Probability Distribution of a 3-State Market Regime Markov Chain

A market is modeled as a Markov chain with 3 regimes: Calm, Volatile, Crisis. Given the transition probability matrix (row i holds the probabilities of moving FROM regime i to each regime), an initial distribution over regimes, and an integer n, return the probability distribution over regimes after exactly n transitions.

Input:
transition = [[0.90, 0.08, 0.02], [0.20, 0.70, 0.10], [0.10, 0.30, 0.60]], initial = [1.0, 0.0, 0.0], n = 2
Output:
[0.828, 0.134, 0.038]
Starting purely in Calm, one step gives [0.90, 0.08, 0.02] (row 0 of the matrix directly). Applying the transition matrix a second time mixes that vector through all three rows, landing at roughly 82.8% Calm, 13.4% Volatile, 3.8% Crisis -- still dominated by Calm but with Crisis probability already compounding faster than Volatile's.
Tap to reveal solution
Hardsliding-windowsegment-tree

Maximum Drawdown Within Every Fixed-Length Window

Given a price series and a window length k, for every contiguous window of k consecutive prices, return the maximum drawdown within that window: the largest drop from a peak to a later trough inside the window (a non-negative number, 0 if the window never falls below its running peak).

Input:
prices=[10,8,7,12,9,15,6], k=4
Output:
[3, 3, 3, 9]
Window [10,8,7,12]: peak 10, worst later trough 7, drawdown 3. Window [15,6] appears in the last window [12,9,15,6]: peak 15 then trough 6, drawdown 9.
Tap to reveal solution
Mediumheap

Running Median of Trade Prices (Two Heaps)

Design a class that ingests trade prices one at a time as they print and, after each ingestion, reports the median of all prices seen so far.

Input:
add(5); add(2); add(8); add(1)
Output:
5, 3.5, 5, 3.5
After [5] median is 5. After [5,2] sorted [2,5] median is the average of both, 3.5. After [5,2,8] sorted [2,5,8] median is 5. After [5,2,8,1] sorted [1,2,5,8] median is the average of the middle two (2 and 5), 3.5.
Tap to reveal solution
Mediumheapdesign

Top-K Most Volatile Tickers in a Streaming Feed

Design a class that ingests (ticker, abs_return) pairs one at a time via update(ticker, abs_return), where abs_return replaces that ticker's previously stored value if it already has one. At any point, top_k() must return the k tickers with the largest current abs_return, in descending order, in better than O(n log n) time overall.

Input:
k=2; update('AAPL',0.02); update('TSLA',0.08); update('MSFT',0.01); top_k() -> ['TSLA','AAPL']; update('AAPL',0.10); top_k() -> ['AAPL','TSLA']
Output:
the k largest current values, descending
Re-updating AAPL to 0.10 replaces its old 0.02 value entirely -- it isn't a second entry -- and immediately changes the top-k ranking.
Tap to reveal solution
Hardprobabilitymarkov-chaindynamic-programming

Gambler's Ruin: Probability of Hitting a Profit Target Before a Stop-Loss

A trader starts with i units of capital (an integer) and makes a sequence of independent unit-sized bets: each wins (+1) with probability p or loses (-1) with probability 1-p. The trader stops upon reaching N units (the profit target) or 0 units (ruin). Compute the probability of hitting the profit target before ruin, starting from i units, for an arbitrary p -- including the fair-coin case p=0.5, where the standard closed-form ratio formula becomes a 0/0 indeterminate and must be handled as a genuinely different case, not just guarded against a division error.

Input:
i=4, N=10, p=0.5
Output:
0.4
At the fair-coin boundary the classic ratio formula degenerates and the true solution is linear in the starting capital: P(i) = i / N = 4/10 = 0.4.
Tap to reveal solution
Harddynamic-programming#188

Maximum Profit With At Most K Buy-Sell Transactions

Given daily prices and an integer k, you may complete at most k buy-then-sell round trips, never holding more than one share at a time and never opening a new position before closing the current one. Return the maximum achievable total profit.

Input:
prices = [3, 2, 6, 5, 0, 3], k = 2
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3). Total 4 + 3 = 7, and no schedule using at most 2 round trips beats that.
Tap to reveal solution
Hardprobabilitydynamic-programming

Expected Events Until Your Order Reaches the Front of the Queue (Random Batch Clears)

Your resting limit order sits behind q other orders in the price-time-priority queue. At each discrete queue event, the front of the queue clears by exactly 1 order with probability p, or by exactly 2 orders with probability 1-p (a single aggressive trade or cancellation can consume two resting orders at once; if fewer than 2 orders remain ahead of you, a 'clear 2' event just clears whatever is left and your order becomes the front). Given q orders ahead of you, return the expected number of events until your order is the new front of the queue.

Input:
q=2, p=0.5
Output:
1.5
Let E[k] be the expected events to clear k orders ahead. E[0]=0, E[1]=1 (clearing 1 or clearing 2 both reach the front from a queue of 1), and E[2] = 1 + 0.5*E[1] + 0.5*E[0] = 1 + 0.5*1 + 0 = 1.5.
Tap to reveal solution
Mediumprobability

Expected Number of Trading Days Until Two Consecutive Up-Days

Model each trading day as closing up with probability p, independent across days. Define the first occurrence of two consecutive up-days as a momentum trigger. Return the expected number of days until that trigger first fires, as a function of p.

Input:
p = 0.5
Output:
6.0
This is the classic 'expected flips to see HH' result -- it takes 6 fair coin flips on average to see two heads in a row.
Tap to reveal solution
Hardheapstreamingdesign#295

Streaming Median Trade Price

Design a tracker that ingests a live stream of trade prices via add(price) and answers median() at any point -- the median of all prices seen so far. Both operations must be fast; add() should not re-sort the whole history on every call.

Input:
add(10); add(20); median(); add(30); median()
Output:
15.0, 20.0
After [10,20] the median is the average of both middle values. After [10,20,30] the median is the single middle value, 20.
Tap to reveal solution
Mediumheapdesign

Running Median of a Live Price Feed

Design a class that ingests a live stream of prices one at a time via add(price) and supports median() returning the current median of all prices seen so far, in O(log n) time per add and O(1) time per query, without re-sorting the full history on each call.

Input:
add(5); add(2); median() -> 3.5; add(7); median() -> 5
Output:
the median of all values added so far
After add(5), add(2), the sorted values are [2,5], median is their average, 3.5. After add(7), sorted values are [2,5,7], median is the middle value, 5.
Tap to reveal solution
Mediumdesignsliding-window

Design a Rolling-Window Circuit Breaker Trigger

Design a class supporting add_price(timestamp, price), which records a new tick, and is_triggered(), which returns True if price has moved by more than a threshold percentage relative to the earliest tick still within the trailing window_seconds -- a simplified single-stock circuit breaker.

Input:
threshold=0.07, window_seconds=300; add ticks at t=0 price=100, t=120 price=103, t=310 price=91; call is_triggered() after each add
Output:
False, False, True
At t=310, the oldest tick still within the 300-second window is (t=120, price=103) since t=0 has aged out; 91 vs 103 is a -11.7% move, past the 7% threshold, so is_triggered() returns True. At t=120 the only reference is t=0 (103 vs 100, +3%), under threshold.
Tap to reveal solution
Hardprobabilitydynamic-programming

Probability a Market Maker's Inventory Hits the Upper Risk Limit Within a Fixed Session

A market maker's inventory starts at 0 and moves +1 with probability p or -1 with probability (1-p) on each tick. The session lasts exactly ticks ticks. The desk has a hard risk limit: if inventory ever reaches upper, trading stops immediately (absorbing); it also stops if inventory ever reaches lower. Return the probability that the session ends by hitting upper at some point within the given number of ticks (hitting lower, or never hitting either barrier, both count as not happening).

Input:
p = 0.5, upper = 2, lower = -2, ticks = 4
Output:
0.375
Forward-propagating the probability mass tick by tick over states {-1,0,1} (with -2 and 2 absorbing) gives a cumulative probability of 0.375 of having hit the upper barrier by tick 4.
Tap to reveal solution
Mediumdynamic-programming

Max Profit With a Mandatory One-Day Cooldown After Selling

Given daily prices, unlimited transactions are allowed (buy then sell, no overlapping holdings), but after selling you cannot buy again the very next day (a one-day cooldown). Return the maximum achievable profit.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), sit out the next day as cooldown, then buy at 0, sell at 2 (profit 2). Total profit 1 + 2 = 3. Holding through to sell at 3 instead looks tempting but its mandatory cooldown blocks the cheap re-entry at 0, netting only 2 overall -- worse than splitting the trade.
Tap to reveal solution
Mediumsliding-window#209

Shortest Window of Trades To Reach a Target Cumulative Volume

Given an array of trade volumes for one trading session and an integer target, return the length of the shortest contiguous window of trades whose volumes sum to at least target. If no such window exists, return -1. (This corresponds to finding the minimum number of consecutive prints needed to accumulate enough volume for a reliable VWAP slice.)

Input:
volumes = [100, 50, 200, 150, 80], target = 280
Output:
2
The window [200, 150] sums to 350 >= 280 with length 2. No single trade reaches 280, so length 2 is the shortest.
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most Two Transactions and a Flat Per-Trade Fee

Given daily prices and a flat fee charged once per completed buy-sell transaction, you may complete at most two transactions (a transaction is one buy followed by one sell; you cannot hold more than one share at a time). Return the maximum achievable profit after fees.

Input:
prices = [3, 2, 6, 5, 0, 3], fee = 1
Output:
5
First transaction buys at index 1 (price 2) and sells at index 2 (price 6) for a gross profit of 4. Second transaction buys at index 4 (price 0) and sells at index 5 (price 3) for a gross profit of 3. Combined gross profit is 7; subtracting the fee once per transaction (2 x 1) leaves a net profit of 5, better than any other non-overlapping pair of transactions.
Tap to reveal solution
Easyheaphash-table

Top K Most Active Tickers by Trade Count

Given a stream of trade events as (ticker, quantity) pairs and an integer k, return the k tickers with the highest total traded quantity, as a list of (ticker, total_quantity) pairs sorted by quantity descending. top_k(k) should be callable repeatedly as more trades keep arriving, without re-sorting the entire ticker universe from scratch each time being the only option.

Input:
add_trade("AAPL",100); add_trade("MSFT",50); add_trade("AAPL",30); add_trade("GOOG",80); top_k(2)
Output:
[('AAPL', 130), ('GOOG', 80)]
AAPL's total is 100+30=130, the highest. GOOG's single trade of 80 is the second highest, ahead of MSFT's 50.
Tap to reveal solution
Hardsliding-windowmonotonic-deque

Shortest Window of Daily P&L That Triggers a Margin Call

Given an array of daily P&L values (positive or negative) and a positive margin threshold m, return the length of the shortest contiguous window of days whose total loss is at least m (i.e. the window's P&L sum is <= -m). Return -1 if no such window exists.

Input:
pnl = [2, -4, -3, 5, -6, 1], m = 7
Output:
2
The window [-4, -3] (days 1-2) sums to -7, a loss of exactly 7, achieved in just 2 days -- no shorter window reaches a loss of 7 or more.
Tap to reveal solution
Harddynamic-programming#188

Best Time to Buy and Sell Stock IV (At Most K Transactions)

Given daily prices and an integer k, maximize total profit using at most k buy-sell transactions. A transaction is one buy followed by a later sell; you must sell before buying again, no overlapping positions.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3); total 7.
Tap to reveal solution
Mediumdesignrate-limiting

Design a Token-Bucket Rate Limiter for an Order-Entry Gateway

Design a rate limiter for an exchange order-entry gateway: allow(timestamp) should return True and consume one token if a token is available, or False if the client has exceeded its allowed order rate. Tokens refill continuously at a fixed rate up to a maximum bucket capacity, matching how real exchange gateways throttle message rates to prevent order-flood incidents.

Input:
capacity=3, refill_rate=1 token/sec; allow(0), allow(0), allow(0), allow(0), allow(1.0)
Output:
True, True, True, False, True
The bucket starts full with 3 tokens; the first three calls at t=0 each consume one, emptying it, so the fourth call at t=0 is rejected. By t=1.0, one second has passed and the bucket refills by 1 token (rate 1/sec), so the fifth call succeeds.
Tap to reveal solution
Hardprobabilitydynamic-programmingmarkov-chain

Probability of Hitting a Profit Target Before a Stop-Loss (Gambler's Ruin)

A trader's running P&L moves in discrete $1 ticks: up with probability p, down with probability 1-p, each tick independent. Starting at P&L 0, return the probability the trader hits a profit target of +T dollars before hitting a stop-loss of -S dollars.

Input:
p=0.5, target=4, stop_loss=2
Output:
0.3333
Symmetric random walk (p=0.5): the classic gambler's ruin closed form gives probability = S / (S+T) = 2/6 = 0.3333, the fair-coin case where the answer is just the ratio of distances.
Tap to reveal solution
Hardprobabilitymarkov-chain

Gambler's Ruin: Probability of Reaching a Profit Target Before Going Broke

A trader starts with i units of capital and makes a series of independent bets, each winning one unit with probability p and losing one unit with probability 1-p. They stop when capital hits 0 (ruin) or reaches N (target). Return the probability they reach the target N before going broke, as a function of i, N, and p.

Input:
i=2, N=5, p=0.5
Output:
0.4
For the fair (p=0.5) case, the classic gambler's ruin result gives probability i/N = 2/5 = 0.4 of reaching the target before ruin.
Tap to reveal solution
Harddesignheapqueue

Design a Price-Time Priority Limit Order Book Matcher

Design a class supporting add_order(order_id, side, price, qty) for a single instrument's limit order book. A BUY order matches against the lowest-priced resting SELL orders whose price is at most the buy's price (and vice versa for a SELL), executing at the RESTING order's price, in strict price-then-time priority. Any unfilled remainder rests in the book. Support get_best_bid() and get_best_ask(), each returning the best resting price on that side or None.

Input:
add_order(1,'SELL',101.0,50); add_order(2,'BUY',101.0,30); add_order(3,'BUY',100.0,100)
Output:
get_best_ask() -> 101.0; get_best_bid() -> 100.0
Order 2 crosses and fills 30 of order 1's 50, leaving 20 resting at 101.0 (still the best ask). Order 3's price of 100.0 doesn't cross the 101.0 ask, so it rests as the best bid instead of matching.
Tap to reveal solution
Mediumdesign

Design a Position Tracker With Realized/Unrealized P&L

Design a class PositionTracker that supports trade(ticker, quantity, price) (quantity positive for buy, negative for sell, using average-cost-basis accounting) and mark(ticker, price) (update the current mark price), and exposes realized_pnl(ticker) and unrealized_pnl(ticker) at any time. Selling more than the current position's size should still be supported (it can go short).

Input:
pt.trade('AAA', 10, 100); pt.trade('AAA', -4, 110); pt.mark('AAA', 105)
Output:
realized_pnl('AAA') -> 40; unrealized_pnl('AAA') -> 30
Buying 10 @ 100 sets avg cost 100. Selling 4 @ 110 realizes (110-100)*4=40 and leaves 6 shares at avg cost 100. Marking at 105 gives unrealized (105-100)*6=30 on the remaining position.
Tap to reveal solution
Mediumprobabilitymath

Probability a Market Maker's Inventory Hits a Risk Limit Before Returning Flat

A market maker's inventory starts at a position start, with absorbing boundaries at 0 (flat) and limit (the desk's hard risk limit), where limit > start > 0. Each tick, inventory moves +1 with probability p or -1 with probability (1-p). Return the probability inventory hits limit before it returns to 0.

Input:
start = 2, limit = 5, p = 0.6
Output:
0.6398
This is the classic gambler's-ruin setup with an asymmetric walk (p != 0.5): the closed-form absorption probability plugs directly to about 0.6398, far higher than the 2/5 = 0.4 you'd get from the symmetric-walk shortcut, because the upward drift from p > 0.5 meaningfully favors reaching the limit first.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Average-Cost-Basis Position Tracker

Design a class PositionTracker, scoped to a single long-only instrument, supporting buy(qty, price), which adds a new purchase lot, and sell(qty, price), which reduces the position by matching against the OLDEST open lots first (FIFO) and returns the realized profit or loss from that sale. Assume sell quantities never exceed the current open position.

Input:
buy(qty=10, price=100); buy(qty=10, price=120); sell(qty=15, price=130)
Output:
350
FIFO matches the sale against the oldest lot first: 10 shares from the price=100 lot (profit 10*(130-100)=300) fully consumes it, then the remaining 5 shares match the price=120 lot (profit 5*(130-120)=50). Total realized profit is 300+50=350, leaving 5 shares open at a cost basis of 120.
Tap to reveal solution
Mediumhash-maplinked-listdesign#146

LRU Cache

Design a data structure that implements an LRU (Least Recently Used) cache with O(1) get and put. When capacity is reached, evict the least recently used key.

Input:
LRUCache(2); put(1,1); put(2,2); get(1); put(3,3); get(2)
Output:
1, then -1
Putting 3 evicts key 2 (least recently used).
Tap to reveal solution
Mediumdynamic-programmingprobabilitymarkov-chain

Expected Number of Ticks Until a Bounded Walk Hits a Barrier

A position's P&L, in whole ticks, starts at integer level s strictly between -n and +n. Each tick moves up by 1 with probability p and down by 1 with probability 1-p. A stop-loss at -n and a take-profit at +n both absorb (the process stops). Compute the expected number of ticks until absorption at either barrier, starting from s.

Input:
n=3, s=0, p=0.5
Output:
9.0
For a symmetric walk with barriers at -n and +n starting at the midpoint 0, the classic gambler's-ruin expected-duration result gives n^2 = 9 -- unlike a probability question, this asks for expected TIME, a different quantity entirely.
Tap to reveal solution
Harddynamic-programming

Best Time to Buy and Sell Stock With At Most Two Transactions and a Flat Fee

Given daily prices and a flat fee charged once per completed round trip, you may complete at most two non-overlapping buy-then-sell transactions (sell before buying again, hold at most one share at a time). Return the maximum achievable profit after fees.

Input:
prices=[3, 3, 5, 0, 0, 3, 1, 4], fee=1
Output:
4
Buy at 0 (index 3), sell at 3 (index 5): profit 3 minus fee 1 = 2. Buy at 1 (index 6), sell at 4 (index 7): profit 3 minus fee 1 = 2. Total 2+2=4 -- one fee shy of the no-fee version's profit of 6, since each of the two round trips pays the fee once.
Tap to reveal solution
Mediumdynamic-programming

Max Profit Holding At Most One Position at a Time, With a One-Day Cooldown After Closing

Given a sequence of daily prices for one instrument, you may open and close a long position as many times as you like, but you may hold at most one position at a time, and after closing a position you must wait one full day (a cooldown) before opening a new one. Return the maximum total profit achievable.

Input:
prices = [1,2,3,0,2]
Output:
3
Buy at index 0 (price 1), sell at index 1 (price 2) for profit 1. Index 2 is the forced cooldown day. Buy at index 3 (price 0), sell at index 4 (price 2) for profit 2. Total profit 1 + 2 = 3, which the DP confirms is optimal.
Tap to reveal solution
Mediumprobabilitydynamic-programming

Gambler's Ruin: Probability of Reaching a Profit Target Before Going Bust

A trader starts with i units of capital and makes repeated unit-sized bets; each bet wins (+1) with probability p and loses (-1) with probability 1-p, independent across bets. The trader stops upon reaching capital N (target) or capital 0 (ruin). Given i, N, and p, return the probability the trader reaches N before going bust.

Input:
i=2, N=5, p=0.5
Output:
0.4
With a fair game (p=0.5) the classic gambler's ruin closed form reduces to i/N: 2/5 = 0.4.
Input:
i=2, N=5, p=0.4
Output:
~0.1896
With a losing edge (p<0.5) ruin probability rises sharply versus the fair case: using r=(1-p)/p=1.5, the closed form gives (1 - r^2) / (1 - r^5) = (1 - 2.25) / (1 - 7.59375) = 0.1896.
Tap to reveal solution
Harddesignheap

Design an Order Book Depth Tracker From Incremental L2 Updates

Design a class OrderBookDepth that consumes incremental level-2 depth updates -- update_bid(price, size) and update_ask(price, size), where size=0 means that price level has been fully removed -- and supports best_bid() and best_ask() queries at any point, each returning the best (highest bid / lowest ask) currently resting price, or None if that side is empty.

Input:
book.update_bid(100.50,300); book.update_bid(100.45,500); book.update_ask(100.55,200); book.update_bid(100.50,0)
Output:
best_bid() -> 100.45 (after the last update); best_ask() -> 100.55
100.50 is removed by the size=0 update, so the best remaining bid falls back to 100.45; the ask side is untouched by any of the bid updates.
Tap to reveal solution
Mediumunion-find

Clustering Assets by Correlation Threshold

Given pairwise asset correlations as (asset_a, asset_b, correlation) triples and a threshold, group assets into clusters such that two assets end up in the same cluster if and only if they are connected by a chain of pairs each at or above the threshold (not every pair is necessarily given). Return the resulting clusters.

Input:
pairs=[("AAPL","MSFT",0.75),("MSFT","GOOGL",0.68),("GOOGL","TSLA",0.30),("XOM","CVX",0.82)], threshold=0.6
Output:
[{"AAPL","MSFT","GOOGL"}, {"TSLA"}, {"XOM","CVX"}]
AAPL-MSFT (0.75) and MSFT-GOOGL (0.68) both clear the threshold, chaining all three into one cluster even though AAPL and GOOGL were never directly compared. GOOGL-TSLA at 0.30 fails the bar, so TSLA stays its own singleton. XOM-CVX (0.82) forms an independent second cluster.
Tap to reveal solution
Mediumprobability

Steady-State Probability of Each Volatility Regime in a Markov Chain

A volatility regime model has 3 states (low, medium, high) with a given daily transition probability matrix. Return the long-run (stationary) probability of being in each regime: the distribution pi such that pi equals pi times the transition matrix and the probabilities sum to 1.

Input:
transition = [[0.90, 0.08, 0.02], [0.15, 0.75, 0.10], [0.05, 0.25, 0.70]]
Output:
[0.5435, 0.3152, 0.1413]
Solving pi = pi @ transition with sum(pi) = 1 gives roughly 54% low-vol, 32% medium-vol, and 14% high-vol days in the long run, even though a single day is far more likely to transition into medium or high vol than this long-run split alone would suggest.
Tap to reveal solution
Mediumdesignbinary-searchhash-map

Design a Time-Based Price Store for Point-in-Time Lookups

Design a store that records a ticker's price at a given timestamp via set(ticker, price, timestamp) (timestamps for a given ticker arrive in strictly increasing order) and answers get(ticker, timestamp) by returning the price at or most recently before that timestamp -- the price that was actually known as of that moment -- or -1 if no price exists for the ticker at or before it, matching a point-in-time price lookup.

Input:
set("AAPL",100,1); set("AAPL",102,3); set("AAPL",105,7); get("AAPL",5); get("AAPL",1); get("AAPL",0)
Output:
102, 100, -1
get(AAPL,5) falls between timestamps 3 and 7, so it returns the most recent price at or before 5, which is 102 from timestamp 3; get(AAPL,1) matches exactly; get(AAPL,0) precedes every recorded timestamp, so it returns -1.
Tap to reveal solution
Harddynamic-programming

Maximum Profit From At Most K Buy-Sell Transactions

Given daily prices and an integer k, find the maximum total profit from at most k non-overlapping buy-then-sell transactions (each buy must occur after the previous sell completes), holding at most one unit at a time.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 for a profit of 4; then buy at 0, sell at 3 for a profit of 3. Total profit 7, and no combination of at most 2 transactions does better.
Tap to reveal solution
Mediumsliding-window#209

Shortest Contiguous Window Whose Trade Volumes Sum to at Least a Target

Given an array of per-minute traded volumes (non-negative integers) and an integer target, return the length of the shortest contiguous window whose volumes sum to at least target. Return 0 if no such window exists.

Input:
volumes = [2,3,1,2,4,3], target = 7
Output:
2
The window [4,3] sums to 7, which meets the target with just 2 minutes -- no shorter window of any starting point reaches 7.
Tap to reveal solution
Hardheap#23

Merge K Sorted Order-Book Update Feeds Into One Time-Ordered Stream

You receive order-book update events from K separate venue feeds, each already sorted by timestamp. Merge all K feeds into a single list of events sorted by timestamp.

Input:
feeds = [[1,4,9], [2,5], [3,6,7,8]]
Output:
[1,2,3,4,5,6,7,8,9]
Each inner list is one venue's already-sorted timestamps; the merged output interleaves all three into one globally sorted stream.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most Two Round-Trip Trades

Given daily prices for one instrument over a quarter, you may complete at most two non-overlapping buy-then-sell round trips (you must sell before buying again). Return the maximum total profit achievable.

Input:
prices=[3,3,5,0,0,3,1,4]
Output:
6
Buy at 0 (index 3), sell at 3 (index 5) for profit 3; buy at 1 (index 6), sell at 4 (index 7) for profit 3. Total 6, better than any single round trip alone.
Tap to reveal solution
Mediumdynamic-programming#714

Max Profit With Unlimited Transactions Under a Percentage Transaction Fee

Given a daily price array and a fee_rate (e.g. 0.1 for a 10% fee), you may buy and sell as many times as you like, one share at a time, fully selling before buying again. Each buy costs price * (1 + fee_rate) and each sell pays out price * (1 - fee_rate) -- the fee is charged on both legs, proportional to notional, not a flat amount. Return the maximum achievable profit.

Input:
prices = [1,3,2,8,4,9], fee_rate = 0.1
Output:
10.3
Buying at 1 and 4, and selling at 3 and 8 (skipping 2 and 9's worse entries), after the 10% fee on every leg, nets 10.3 total -- less than the no-fee optimum of 13, since every round trip now pays away roughly 20% of its notional in fees.
Tap to reveal solution
Mediumdynamic-programmingprobability

Probability of Hitting a Stop-Loss Before a Take-Profit Within N Ticks

A position's P&L moves up one tick with probability p and down one tick with probability 1-p, starting at 0. Given a stop-loss at -b, a take-profit at +a, and a maximum horizon of N ticks after which the position is flattened at whatever level it's at (neither barrier counted as hit), compute the probability the stop-loss is hit strictly before the take-profit and before the horizon runs out.

Input:
a=2, b=2, p=0.5, n=3
Output:
0.375
With only 3 ticks available and symmetric barriers 2 ticks away, several paths never reach either barrier in time (e.g. up-down-up ends at +1, no barrier hit) -- unlike the unbounded gambler's-ruin formula, the finite horizon leaves real probability mass on 'neither hit yet.'
Tap to reveal solution
Mediumprobabilitymathdynamic-programming

Gambler's Ruin: Probability of Hitting a Profit Target Before a Stop-Loss

A trader's running P&L moves in discrete +1 or -1 ticks, up with probability p and down with probability 1-p each step, starting at 0. Given a stop-loss at -a (a > 0 ticks) and a profit target at +b (b > 0 ticks), compute the probability the P&L hits +b before it hits -a. Handle both p=0.5 and p != 0.5 correctly.

Input:
p=0.5, a=3, b=5
Output:
0.375
The classic symmetric gambler's ruin result: with a fair coin, the probability of reaching +b before -a starting from 0 is a / (a + b) = 3 / 8 = 0.375.
Tap to reveal solution
Hardgraphbellman-ford

Detecting FX Triangular Arbitrage via Negative-Cycle Detection

Given a list of currency pairs and their exchange rates as (from_currency, to_currency, rate) triples (rate = units of to_currency received for 1 unit of from_currency), determine whether a triangular -- or longer cyclic -- arbitrage opportunity exists: a sequence of conversions starting and ending at the same currency that yields strictly more than you started with.

Input:
rates=[("USD","EUR",0.9), ("EUR","GBP",0.8), ("GBP","USD",1.4)]
Output:
True
1 USD -> 0.9 EUR -> 0.9*0.8=0.72 GBP -> 0.72*1.4=1.008 USD, ending with more than the 1 USD started with -- an arbitrage loop.
Tap to reveal solution
Mediumsliding-window

Smallest Contiguous Window of Fills Covering Every Required Venue

Given a sequence of fills in execution order, each tagged with the venue it executed on, and a set of required venues, return the length of the smallest contiguous window of fills containing at least one fill from every required venue. Return 0 if no such window exists.

Input:
venues = ["NYSE", "NASDAQ", "NYSE", "ARCA", "NASDAQ"], required = {"NYSE", "ARCA", "NASDAQ"}
Output:
3
The window [NASDAQ, NYSE, ARCA] (indices 1-3) and the window [NYSE, ARCA, NASDAQ] (indices 2-4) are both length 3 and cover all three required venues; no shorter window does.
Tap to reveal solution
Easyheap

Top K Largest Daily P&L Values in a Stream

Design a class that ingests a stream of daily P&L values one at a time and, after each ingestion, can report the k largest P&L values seen so far (k is fixed when the tracker is created).

Input:
k = 3; add(5); add(-2); add(9); add(1); add(7); top_k()
Output:
[5, 7, 9]
After all five values [5, -2, 9, 1, 7], the three largest are 5, 7, and 9. A min-heap of size k keeps exactly those three without ever sorting the full history.
Tap to reveal solution
Harddynamic-programmingbinary-searchsorting

Maximum Profit From Non-Overlapping Trading Windows

You're given n candidate trading windows, each defined by (start_day, end_day, profit) -- a pre-computed profit you'd realize by holding a position from start_day to end_day. You may select any number of windows as long as no two selected windows overlap in time (end_day of one must be <= start_day of the next). Return the maximum total profit achievable.

Input:
windows=[(1,3,50),(2,5,20),(4,6,70),(6,8,60)]
Output:
180
Picking (1,3,50), (4,6,70), (6,8,60) gives 50+70+60=180. Window (4,6) ending exactly where (6,8) starts is allowed -- touching, not overlapping. (2,5,20) overlaps both (1,3) and (4,6), so including it instead of either would only lower the total.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Expected Number of Ticks Until an Asymmetric Inventory Walk Hits Either Bound

A market maker's inventory moves by +1 with probability p and -1 with probability 1-p on every tick, starting at 0, with absorbing bounds at -N and +N (the position-limit breach in either direction). Given N, p, and a starting inventory, return the expected number of ticks until the walk first reaches either bound.

Input:
N = 3, p = 0.55, start = 0
Output:
8.767
A slight upward drift (p > 0.5) shortens the expected time to absorption relative to the driftless case -- at p = 0.5 the same N = 3 setup gives exactly N^2 = 9 ticks by the classic symmetric gambler's ruin formula, and 8.767 is a bit faster thanks to the drift nudging the walk toward a bound sooner on average.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Ticks Until a Resting Limit Order at the Back of the Queue Gets Filled

A resting limit order sits k orders behind the front of its price level's queue. On each tick, independently: with probability p the order currently at the front fills and every order (including yours, if you're not yet at the front) moves up one spot; with probability c (only relevant while you're not at the front) one of the orders strictly ahead of you cancels, also moving you up one spot. Once you reach the front, each tick fills your own order with probability p. Compute the expected number of ticks until your order executes, given p, c, and k.

Input:
p = 0.1, c = 0.05, k = 3
Output:
30.0
Each step ahead of the front costs an expected 1/(p+c) ticks to close (fill-at-front or cancel-ahead each advance you one spot), plus 1/p expected ticks once you're at the front and waiting for your own geometric fill.
Tap to reveal solution
Mediumheapdesign

Running Median Trade Price via Two Heaps

Design a class MedianTracker supporting add_price(price), which ingests one trade price at a time, and median(), which returns the median of every price ingested so far. Both methods must avoid re-sorting the whole history on every call.

Input:
add_price(101); add_price(105); median(); add_price(99); median()
Output:
103.0, 101.0
After [101, 105] the median is the average of both (103.0). After adding 99, the sorted set is [99, 101, 105] and the median is the middle value, 101.0.
Tap to reveal solution
Mediumprobabilitymathmatrix-exponentiation

Market Regime Distribution After N Days via Matrix Exponentiation

Given a k-by-k Markov transition matrix P for daily market regimes (P[i][j] is the probability of moving from regime i to regime j in one day), a starting regime index, and a horizon N (which may be very large), compute the probability distribution over regimes after N days.

Input:
P=[[0.9,0.1],[0.2,0.8]], start=0, N=2
Output:
[0.83, 0.17]
P^2 = [[0.83,0.17],[0.34,0.66]]; starting in regime 0, the distribution after 2 days is row 0 of P^2.
Tap to reveal solution
Mediumdynamic-programming

Maximum Stock Profit With a Cooldown Day After Selling

Given daily prices, unlimited transactions are allowed (never hold more than one share at a time), but after selling you cannot buy again the very next day -- you must wait at least one cooldown day before your next buy. Find the maximum achievable total profit.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at 1, sell at 2 (profit 1), the cooldown day is forced next, then buy at 0 and sell at 2 (profit 2). Total profit 1+2=3, and no plan obeying the cooldown beats it.
Tap to reveal solution
Hardsliding-window#862

Shortest Window of Signed Trade Volumes Reaching a Target Sum

Given a sequence of signed trade volumes (positive = an executed trade, negative = a cancellation reversing previously counted volume), find the length of the shortest contiguous window whose sum is at least a target. Return -1 if no such window exists.

Input:
volumes = [2, -1, 2, 4, 3], target = 7
Output:
2
The window [4, 3] (indices 3-4) sums to exactly 7 in just 2 trades -- shorter than [2,-1,2,4] (4 trades, sum 7) or [2,4,3] (3 trades, sum 9).
Tap to reveal solution
Mediumdesignhash-map

Design an Average-Cost Position Tracker

Design a tracker supporting buy(ticker, qty, price) and sell(ticker, qty, price) that maintains, per ticker, the current share count and volume-weighted average cost of the open position, and returns the REALIZED P&L generated by each sell using average-cost-basis accounting (not FIFO or LIFO lot matching). Assume sells never exceed the current position. Support position(ticker) returning (qty, avg_cost).

Input:
buy('AAPL',100,150); buy('AAPL',50,180); sell('AAPL',80,200)
Output:
avg_cost=160.0 before the sell; realized=3200.0; remaining position (70, 160.0)
Average cost after both buys is (100*150 + 50*180) / 150 = 160. A sell books realized P&L against that average cost and leaves it UNCHANGED -- only the quantity shrinks -- so realized = 80 * (200 - 160) = 3200.
Tap to reveal solution
Mediumheap

Kth Largest Trade Size in a Streaming Order Flow

You receive trade sizes one at a time from a live feed. Implement a class that supports add(size) and returns the kth largest trade size seen so far after every addition, for a fixed k decided at construction time.

Input:
k = 3; add(4); add(5); add(8); add(2); add(10)
Output:
None, None, 4, 4, 5
The 3rd largest only exists once 3 trades have arrived. After [4,5,8] it's 4. Adding 2 doesn't change it (still 4). Adding 10 makes the top three [10,8,5], so the 3rd largest becomes 5.
Tap to reveal solution
Mediumarraygreedy#122

Best Time to Buy and Sell Stock II (Unlimited)

You may complete as many transactions as you like (buy one and sell one share many times). You may not engage in multiple transactions simultaneously (must sell before buying again). Maximize total profit.

Input:
prices = [7,1,5,3,6,4]
Output:
7
Buy 1 sell 5 (+4), buy 3 sell 6 (+3).
Input:
prices = [1,2,3,4,5]
Output:
4
Capture every up-day.
Tap to reveal solution
Mediumheap

Top-K Symbols by Cumulative Traded Volume

Design a class VolumeTracker supporting add_trade(symbol, volume), which accumulates traded volume per symbol over time, and top_k(k), which returns the k symbols with the highest cumulative volume so far, without re-sorting the entire universe of symbols on every query.

Input:
add_trade('AAPL', 100); add_trade('MSFT', 250); add_trade('AAPL', 50); add_trade('TSLA', 400); top_k(2)
Output:
['TSLA', 'MSFT']
Cumulative volumes are AAPL=150, MSFT=250, TSLA=400. The two highest are TSLA (400) and MSFT (250).
Tap to reveal solution
Hardsliding-windowhash-map

Minimum Window Containing All Required Tickers

Given a chronological list of ticker symbols representing a trade tape, and a set of required tickers, find the shortest contiguous window (by index) of the tape that contains at least one trade for every required ticker. Return the window as (start, end) indices (end exclusive), or None if no such window exists.

Input:
tape=["AAPL","MSFT","AAPL","GOOG","MSFT","AAPL"], required={"AAPL","GOOG","MSFT"}
Output:
(1, 5)
tape[1:5] = ["MSFT","AAPL","GOOG","MSFT"] contains all three required tickers and has length 4, the shortest such window -- no length-3 window covers AAPL, GOOG, and MSFT simultaneously.
Tap to reveal solution
Mediumheap

Running Median of a Live Trade Price Stream

Design a class MedianTracker that processes a live stream of trade prices via add_price(price) and supports median(), which returns the median of all prices seen so far, without re-sorting the full history on every query.

Input:
add_price(5); add_price(15); median(); add_price(1); median()
Output:
10.0, then 5.0
After [5, 15], the sorted list is [5, 15], so the median is (5+15)/2 = 10.0. After adding 1, the sorted list is [1, 5, 15], so the median is the middle element, 5.0.
Tap to reveal solution
Mediumdesignhash-map

Design a Limit Order Book Matcher With Self-Trade Prevention (STP)

Extend a standard price-time-priority limit order matcher with self-trade prevention: an incoming order must never match against a resting order that belongs to the same account. Support add_order(order_id, account_id, side, price, qty), which attempts to match immediately against the opposite side (best price first, then earliest resting time), skipping over -- never trading against -- any resting order from the same account_id, and resting whatever quantity doesn't get filled. Return the list of (resting_order_id, fill_qty) trades produced.

Input:
add_order(1,'acct_A','buy',100,50); add_order(2,'acct_A','sell',100,50); add_order(3,'acct_B','sell',100,50)
Output:
order 2 -> []; order 3 -> [(1, 50)]
Order 2 is acct_A trying to sell at 100 while acct_A's own order 1 rests as a buy at 100 -- STP means order 2 is not allowed to trade against order 1, so it rests instead with zero fills. Order 3, from a different account, does cross with order 1 and fills 50 at 100.
Tap to reveal solution
Mediumdynamic-programming

Max Profit With a One-Day Cooldown After Selling

Given daily prices for one instrument, you may buy and sell any number of times (never holding more than one unit at a time), but after selling you must wait one full day before buying again, modeling a settlement cooldown. Return the maximum total profit.

Input:
prices = [1,2,3,0,2]
Output:
3
Buy at 1 (day 0), sell at 2 (day 1) for profit 1, day 2 is the forced cooldown, buy at 0 (day 3), sell at 2 (day 4) for profit 2. Total profit 1 + 2 = 3, and no other combination that respects the cooldown beats it.
Tap to reveal solution
Mediumheap

Kth Largest Resting Order Size in a Live Order Book Stream

You receive a stream of order events, each either add(order_id, size) placing a new resting order, or cancel(order_id) removing a previously added one. After each event, report the Kth largest size currently resting in the book (or None if fewer than K orders are resting).

Input:
k = 2; add(1,100); add(2,250); add(3,80); cancel(2); add(4,300)
Output:
None, None, 80, 100, 100
After add(1): only 1 order, no 2nd largest -> None. After add(2): sizes {100,250}, 2nd largest 100 -> wait, sorted desc [250,100], 2nd largest is 100. After add(3): sizes {100,250,80}, 2nd largest 100. After cancel(2): sizes {100,80}, 2nd largest 80. After add(4): sizes {100,80,300}, 2nd largest 100.
Tap to reveal solution
Hardprobabilitymath

Expected Number of Ticks for an Asymmetric Walk to Hit a Take-Profit or Stop-Loss

A position's P&L in ticks starts at 0, with absorbing barriers at -stop (stop-loss) and +profit (take-profit), where both are positive integers. Each tick, P&L moves +1 with probability p or -1 with probability (1-p). Return the expected number of ticks until the position hits either barrier.

Input:
stop = 3, profit = 5, p = 0.5
Output:
15.0
Symmetric gambler's-ruin expected-duration formula: E[T] = stop * profit for p = 0.5, giving 3 * 5 = 15 ticks on average before the walk is absorbed at either barrier.
Tap to reveal solution
Mediumheap

K Closest Resting Limit Orders to the Current Mid-Price

Given a list of resting limit order prices on both sides of the book and the current mid-price, return the k order prices closest to the mid-price, with ties broken by the lower price first.

Input:
prices = [98, 99, 101, 105, 97], mid = 100, k = 3
Output:
[99, 101, 98]
Distances to mid are 98->2, 99->1, 101->1, 105->5, 97->3. The 3 closest are 99 and 101 (tied at distance 1, lower price 99 first) and 98 (distance 2); 105 and 97 are farther and excluded.
Tap to reveal solution
Mediumheapdesign

Running Median of a Live Trade Price Stream (Two Heaps)

Design a structure that ingests trade prices one at a time from a live tape via add(price) and can report the median of all prices seen so far via median(), without re-sorting the full history on every call.

Input:
add(5); add(2); median(); add(8); median()
Output:
3.5, 5.0
After [5,2] the sorted history is [2,5], median 3.5. After [5,2,8] the sorted history is [2,5,8], median 5.0.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Trades Until a Strategy Hits Its Profit Target or Stop Loss

A strategy's cumulative P&L moves up one unit with probability p or down one unit with probability 1-p on each trade, independently. Trading stops the moment cumulative P&L reaches +target (profit target) or -stopLoss (stop loss). Compute the probability the profit target is hit first, and the expected number of trades until the strategy stops.

Input:
p = 0.5, target = 5, stopLoss = 5
Output:
prob_target_first = 0.5, expected_trades = 25.0
For a fair (p = 0.5) walk this is the classic gambler's ruin: by symmetry the target and stop loss are equally likely to be hit first, and the expected duration is target * stopLoss.
Tap to reveal solution
Harddynamic-programming

Minimum Cost to Acquire a Target Position Under a Per-Day Buy Cap

Given a forecasted price for each of n future trading days and a per-day maximum number of shares you're allowed to buy, return the minimum total cost to acquire exactly a target number of shares by day n, buying only on the given days (no selling, no short positions).

Input:
prices = [10, 8, 12, 9], daily_cap = 5, target = 12
Output:
105
Sorted by price ascending, the cheapest days are 8, 9, 10, 12. Greedily filling the cap from cheapest to most expensive: 5 shares at 8, then 5 shares at 9, then the last 2 shares at 10 -- 5*8 + 5*9 + 2*10 = 40 + 45 + 20 = 105. Any swap that takes shares from a cheaper day and buys them on a more expensive day instead can only raise the total, so this is optimal.
Tap to reveal solution
Mediumdynamic-programming#714

Best Time to Buy and Sell Stock with Transaction Fee

Maximize profit trading a single stock with unlimited transactions, where every completed round trip (one buy plus one sell) costs a fixed fee. Unlike the cooldown variant, there is no waiting period between a sell and the next buy.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
8
Buy at 1, sell at 8 (profit 7 - 2 fee = 5); buy at 4, sell at 9 (profit 5 - 2 fee = 3); total 8. Cheaper to hold through the dip at 2 than pay a second fee immediately.
Tap to reveal solution
Mediumprobability

Expected Number of Trades Until Two Consecutive Profitable Trades

A trading strategy wins each trade independently with probability p (and loses with probability 1-p). Return the expected number of trades needed to see two profitable trades IN A ROW for the first time.

Input:
p = 0.5
Output:
6.0
This is the classic expected-flips-to-get-two-heads-in-a-row result: E = (1 + p) / p^2 = 1.5 / 0.25 = 6.0.
Tap to reveal solution
Mediumsliding-window

Longest Trading Window With At Most K Losing Days

Given an array of daily P&L values and an integer k, return the length of the longest contiguous window of days containing at most k days with negative P&L (losing days).

Input:
pnl = [2, -1, -1, 3, 4, -1, 5], k = 1
Output:
4
The window [3, 4, -1, 5] contains exactly one losing day. No longer window in the array stays at or under that limit.
Tap to reveal solution
Harddesignheap

Design a Limit Order Book Supporting Cancel and Priority-Losing Price Amendment

Design a price-time-priority limit order book for one instrument supporting add_buy(order_id, price, qty) and add_sell(order_id, price, qty) (each crossing immediately against the opposite side), cancel(order_id) (removes a still-resting order), and amend_price(order_id, new_price) (re-quotes a resting order at a new price). A call to amend_price must NOT preserve the order's original time priority -- it re-enters at the back of the queue at its new price, exactly like a real exchange treats any price change as forfeiting queue position.

Input:
add_sell(1,101.0,100); add_sell(2,101.0,50); amend_price(1,101.0); add_buy(3,101.0,120)
Output:
[(2,101.0,50), (1,101.0,70)]
Order 1 re-quotes and loses its place in the queue even though the price is unchanged, so order 2 -- never amended -- now has priority and fills first for its full 50 shares, with order 1 filling the remaining 70.
Tap to reveal solution
Mediumprobabilitymath

Probability a Market Maker's Inventory Hits the Risk Limit Before Flat

A market maker's inventory starts at i shares, with 0 < i < N. Each tick, a buy fill increases inventory by 1 (probability p) or a sell fill decreases it by 1 (probability 1-p), independently. Trading halts the instant inventory hits 0 (back to flat) or N (risk limit breach, forcing a hedge). Given N, i, and p, compute the probability the risk limit is hit before the desk gets back to flat.

Input:
N=10, i=4, p=0.5
Output:
0.4
For a fair (p=0.5) walk, the absorption probability reduces to the simple ratio i/N = 4/10 = 0.4 -- the walk is equally likely per unit distance to drift either way.
Tap to reveal solution
Harddynamic-programming

Max Profit With a Settlement Cooldown After Each Sale

Given daily prices for one instrument and an integer cooldown, you may buy and sell as many times as you like (never holding more than one unit at a time), but after selling you must wait cooldown full days before your proceeds are free to fund another buy. Return the maximum total profit achievable.

Input:
prices = [1,2,3,0,2], cooldown = 1
Output:
3
Buy at 1, sell at 2 (profit 1), wait out the 1-day cooldown, buy at 0, sell at 2 (profit 2). Total profit 1 + 2 = 3.
Input:
prices = [1,2,3,0,2], cooldown = 2
Output:
2
With a longer 2-day settlement period there isn't time to clear the first sale's cooldown and still catch the second dip-and-recover, so the best achievable is a single round trip: buy at 1, sell at 3, profit 2.
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most K Round-Trip Trades

Given daily prices for one instrument and an integer k, you may complete at most k buy-then-sell round trips, never holding more than one unit at a time and always selling before buying again. Return the maximum total profit achievable.

Input:
prices = [3,2,6,5,0,3], k = 2
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3). Two round trips, total profit 4 + 3 = 7, and no combination of at most 2 round trips beats it.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Window of Trades Under a Participation Volume Cap

Given a chronological list of trade sizes volumes for one name and a cap max_volume, return the length of the longest contiguous subarray whose SUM of volumes does not exceed max_volume. Assume every individual volume is itself <= max_volume.

Input:
volumes=[200,300,100,400,100], max_volume=600
Output:
3
The window [300,100,400] sums to 800, too high. The window [100,400,100] (indices 2-4) sums to 600, exactly at the cap, and has length 3 -- no longer valid window exists.
Tap to reveal solution
Mediumsliding-window#340

Longest Tick Window Touching At Most K Distinct Venues

Given a sequence of venue IDs, one per tick (where a trade executed), return the length of the longest contiguous window of ticks that includes trades from at most k distinct venues. This bounds how much cross-venue reconciliation a rolling analytics window has to handle at once.

Input:
venues = [1, 2, 1, 3, 4], k = 2
Output:
3
The window [1,2,1] touches only {1,2}, two distinct venues, length 3. Extending either direction brings in a third venue, so 3 is the longest window with at most 2 distinct venues.
Tap to reveal solution
Mediumprobabilitymarkov-chainmath

Probability of Hitting a Profit Target Before a Stop-Loss

A position's P&L, in whole ticks, starts at integer level s strictly between -n and +n. Each tick moves up by 1 with probability p and down by 1 with probability 1-p. A stop-loss at -n and a take-profit at +n both absorb (the process stops). Return the probability the process is absorbed at +n rather than -n.

Input:
n=3, s=0, p=0.5
Output:
0.5
A symmetric random walk starting exactly at the midpoint between two equidistant barriers hits either barrier with equal probability by the classic gambler's-ruin result.
Input:
n=3, s=0, p=0.6
Output:
0.6730
With an upward drift (p > 0.5), the closed-form ratio-based formula applies instead of the symmetric 50/50 case.
Tap to reveal solution
Hardprobabilitydynamic-programming

Probability a P&L Path Never Goes Negative Over N Trades

A trader's cumulative P&L moves by +1 tick with probability p and -1 tick with probability 1-p on each of n trades, starting at 0. Compute the probability that the cumulative P&L never goes strictly negative at any point across all n trades (it may touch exactly 0). Give an approach that works for a general p, not just p=0.5.

Input:
p=0.5, n=2
Output:
0.5
Four equally likely paths: ++ (never negative), +- (touches 0, never negative), -+ (goes to -1, DOES go negative), -- (goes negative). Two of four paths stay non-negative throughout: probability 0.5.
Tap to reveal solution
Mediumdesignqueuestreaming

Design a Sliding-Window VWAP Tracker

Design a tracker, constructed with a fixed window_size (number of most recent trades), that ingests a stream of trades via trade(price, size) and answers vwap() queries for the volume-weighted average price over the last window_size trades -- both operations O(1) amortized, not O(window_size) per query.

Input:
window_size=2; trade(10,100); trade(11,50); trade(9,200); vwap()
Output:
9.4
Only the last 2 trades count: (11*50 + 9*200) / (50 + 200) = 2350 / 250 = 9.4.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Buy/Sell Transactions

Given daily prices for a stock and an integer k, return the maximum profit achievable using at most k buy-then-sell transactions (never holding more than one share at a time, and a sale must happen before the next buy).

Input:
k=2, prices=[3,2,6,5,0,3]
Output:
7
Buy at index 1 (price 2), sell at index 2 (price 6) for profit 4. Buy at index 4 (price 0), sell at index 5 (price 3) for profit 3. Total profit using 2 transactions: 4 + 3 = 7, and no combination of at most 2 transactions beats that.
Tap to reveal solution
Mediumheap

Running Median Trade Price from a Live Tape (Two Heaps)

You receive a live stream of trade prices for one instrument. After each new trade, report the current running median price across all trades seen so far, without re-sorting the full history on every update.

Input:
add(5); add(15); add(1); add(3)
Output:
5, 10.0, 5, 4.0
After [5]: median 5. After [5,15]: even count, median is the average of the two middle values, (5+15)/2=10.0. After [5,15,1]: sorted [1,5,15], median 5. After [5,15,1,3]: sorted [1,3,5,15], median (3+5)/2=4.0.
Tap to reveal solution
Hardprobabilitydynamic-programming

Probability an Inventory Random Walk Hits Its Risk Limit Within T Steps (Reflecting at Zero)

A market maker's signed inventory starts at i and, each step, moves up by 1 with probability p or down by 1 with probability 1-p -- except at inventory 0, where a down-move is not allowed to go negative and instead reflects (the walk stays at 0). Trading is forced to stop the instant inventory reaches a hard risk limit N (an absorbing barrier). Given N, i, p, and a horizon T, compute the probability the walk is absorbed at N at or before step T.

Input:
N=2, i=1, p=0.5, T=3
Output:
0.625
From i=1 (one below the limit), the walk is absorbed with probability 0.5 on step 1 alone. The remaining probability mass bounces between 0 and 1 off the reflecting boundary, contributing another 0.125 of absorption probability by step 3, for a cumulative 0.625.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Number of Rounds to Hit a Profit Target or Stop-Out

A trader starts with i units of capital (integer). Each round, capital increases by 1 with probability p and decreases by 1 with probability 1-p. Trading stops when capital hits 0 (stop-out) or N (profit target). Return the expected number of rounds until trading stops, given starting capital i, target N, and win probability p.

Input:
i=2, N=4, p=0.5
Output:
4.0
For a fair coin, the classic result for expected absorption time of a symmetric random walk on {0..N} is i*(N-i) = 2*(4-2) = 4.
Tap to reveal solution
Mediumgraphtopological-sortdfs#207

Course Schedule (Cycle in DAG)

There are numCourses courses labeled 0..numCourses-1. You are given prerequisites where prerequisites[i] = [a, b] means you must take b before a. Return true if you can finish all courses (i.e. the dependency graph has no cycle).

Input:
numCourses = 2, prerequisites = [[1,0]]
Output:
true
Input:
numCourses = 2, prerequisites = [[1,0],[0,1]]
Output:
false
Cycle.
Tap to reveal solution
Mediumsliding-windowhash-map

Longest Trading Window Touching At Most K Distinct Sectors

Given a chronological array of sector labels, one per trade, find the length of the longest contiguous window of trades that touches at most K distinct sectors -- used to bound how concentrated a rolling execution schedule is allowed to be.

Input:
sectors=['Tech','Tech','Energy','Fin','Energy','Energy'], k=2
Output:
4
The window ['Energy','Fin','Energy','Energy'] (indices 2-5) touches exactly 2 distinct sectors (Energy, Fin) and has length 4; no longer window stays within 2 distinct sectors.
Tap to reveal solution
Mediumarraysortingintervals#56

Merge Intervals

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Input:
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output:
[[1,6],[8,10],[15,18]]
Input:
intervals = [[1,4],[4,5]]
Output:
[[1,5]]
Touching intervals merge.
Tap to reveal solution
Mediumdynamic-programming

Max Profit With At Most Two Transactions and a Fixed Commission Per Trade

Given an array of daily prices, a flat commission charged once per completed round-trip transaction (not separately on the buy and the sell), and the constraint that you may complete at most two non-overlapping buy-sell transactions, return the maximum achievable profit net of commission.

Input:
prices = [3, 8, 1, 9, 2, 10], commission = 2
Output:
12
Buy at 1 (index 2), sell at 9 (index 3): net profit 9 - 1 - 2 = 6, using the first transaction slot. Buy at 2 (index 4), sell at 10 (index 5): net profit 10 - 2 - 2 = 6, using the second slot. Total net profit across both transactions: 12 -- better than any pairing that uses the day-0 price of 3 as an entry.
Tap to reveal solution
Mediumprobabilitymarkov-chainmath

Probability of Hitting a Profit Target Before a Stop-Out

A trader's capital moves on an integer grid from 0 to N. Starting at integer capital i (0 < i < N), each round capital increases by 1 with probability p and decreases by 1 with probability 1-p. Trading stops the instant capital reaches 0 (stop-out) or N (profit target). Return the probability of reaching the profit target N before the stop-out.

Input:
i=4, N=10, p=0.5
Output:
0.4
For a fair coin (p=0.5), the classic gambler's-ruin result is simply i/N = 4/10 = 0.4 -- capital is a martingale, so the hitting probability is exactly linear in the starting point.
Tap to reveal solution
Hardsliding-windowmonotonic-deque

Sliding Window Maximum of Best-Bid Depth

Given an array depth where depth[i] is the resting size at the best bid after the i-th order-book update, and a window size w, return an array output where output[i] is the maximum depth over the window depth[i:i+w], for every valid window position.

Input:
depth=[8, 3, 11, 11, 6, 2, 14], w=3
Output:
[11, 11, 11, 11, 14]
Windows [8,3,11] -> 11, [3,11,11] -> 11, [11,11,6] -> 11, [11,6,2] -> 11, [6,2,14] -> 14.
Tap to reveal solution
Mediumdynamic-programming#309

Best Time to Buy and Sell Stock with Cooldown

Maximize profit trading a single stock with unlimited transactions, but after selling you must wait one full day (cooldown) before buying again -- you cannot buy on the day immediately following a sell.

Input:
prices = [1,2,3,0,2]
Output:
3
Buy day0 (1), sell day1 (2) for +1; cooldown day2; buy day3 (0), sell day4 (2) for +2; total profit 3, respecting the one-day cooldown after each sell.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With a Per-Trade Fee

Given daily prices and a fixed fee charged once per completed round-trip (buy then sell), you may transact as many times as you like but must sell before buying again. Return the maximum achievable profit.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
8
Buy day0 (1), sell day3 (8): profit 7-2=5 fee-adjusted. Buy day4 (4), sell day5 (9): profit 5-2=3. Total 5+3=8.
Tap to reveal solution
Hardsliding-windowhash-map

Minimum Window Covering a Required Set of Tickers

Given a chronological list of ticker symbols printed by a trade feed and a required set of tickers a strategy needs a fresh quote for, find the shortest contiguous window of the print sequence that contains at least one print for every required ticker.

Input:
prints=["AAPL","MSFT","AAPL","GOOG","MSFT"], required={"AAPL","GOOG","MSFT"}
Output:
indices 2-4 (AAPL, GOOG, MSFT), length 3
The window from index 2 to 4 (AAPL, GOOG, MSFT) is the shortest contiguous stretch containing all three required tickers at least once; no shorter window covers all three.
Tap to reveal solution
Mediumheapmerge-k-sorted

Merge K Sorted Price Feeds

You receive K price feeds for the same symbol from K different venues. Each feed is a list of (timestamp, price) ticks already sorted by timestamp within itself, but the feeds interleave arbitrarily against each other. Merge all K feeds into a single stream sorted by timestamp.

Input:
feeds = [[(1,100.0),(4,101.5)], [(2,99.5),(3,102.0)]]
Output:
[(1,100.0),(2,99.5),(3,102.0),(4,101.5)]
Pull the globally-earliest unread tick across all feeds each step.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Round-Trip Trades

Given daily prices for one instrument and an integer k, return the maximum profit achievable using at most k non-overlapping buy-then-sell round trips (you must sell before buying again).

Input:
prices = [3, 2, 6, 5, 0, 3], k = 2
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3). Total 7, using exactly 2 of the allowed round trips.
Tap to reveal solution
Mediumstringsliding-windowhash-map#3

Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Input:
s = "abcabcbb"
Output:
3
"abc"
Input:
s = "bbbbb"
Output:
1
Input:
s = "pwwkew"
Output:
3
"wke"
Tap to reveal solution
Harddesignheaporder-book

Design a Price-Time Priority Limit Order Book

Design a simplified limit order matching engine supporting add_order(side, price, size) for BUY or SELL limit orders. On arrival, an order matches against the best resting orders on the opposite side while price is favorable (buy price >= resting ask, or sell price <= resting bid), executing at the RESTING order's price, in time priority among orders at the same price level. Any unfilled remainder rests in the book. Return the list of fills produced by each new order.

Input:
add_order(SELL,100,10); add_order(SELL,100,5); add_order(BUY,101,12)
Output:
[(100, 10), (100, 5), 3 unfilled resting as a BUY at 101]
The incoming buy at 101 crosses both resting sells at 100 (better than its limit), filling the earlier-arrived 10 lots first (time priority), then 5 more of the requested 12, leaving 3 lots resting as a new bid.
Tap to reveal solution
Mediumdynamic-programming

Max Profit With a Mandatory One-Day Cooldown After Selling (T+1 Settlement)

Given daily prices for one instrument, you may hold at most one share at a time. After selling, settlement rules force a mandatory one-day cooldown during which you may not buy again (you may still just stay flat). Return the maximum achievable profit.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy day 0 at 1, sell day 1 at 2 (profit 1), cooldown on day 2, buy day 3 at 0, sell day 4 at 2 (profit 2). Total profit 1 + 2 = 3. Selling at the day-2 peak of 3 instead would use up the only other share-eligible day on a cooldown with no time left to re-buy and sell again at 2, netting less.
Tap to reveal solution
Mediumsliding-window

Longest Window Where Order Imbalance Stays Within a Band

Given an array of order-book imbalance readings (one per tick) and an integer limit, return the length of the longest contiguous subarray in which the maximum imbalance minus the minimum imbalance is at most limit.

Input:
imbalance = [4,8,5,1,7,9], limit = 3
Output:
3
The window [4,8,5] (indices 0-2) has max 8, min 4, range 4, which exceeds limit 3. The window [8,5,1] has range 7, also too wide. The qualifying longest window is [1,7] extended... checking all windows, [4,5] is length 2; the actual longest window with range <= 3 is [7,9] extended by nothing further, or [5,1] range 4 (fails). The longest valid window here is length 3: no window of length 4+ has max-min <= 3.
Tap to reveal solution
Mediumsliding-windowprefix-sum

Longest Trading Window Within a Cumulative Slippage Budget

Given the per-trade slippage cost (in bps, all non-negative) for a sequence of executed child orders and a total slippage budget, find the length of the longest contiguous run of trades whose slippage costs sum to at most the budget.

Input:
slippage=[2,1,4,3,1,2], budget=6
Output:
3
The window [4,3,1] no longer works (sums to 8 with 4+3, already over before adding 1), but [1,4] sums to 5 and extending to [1,4,3] sums to 8, over budget; the actual best window is [3,1,2] summing to 6, achieving length 3 -- checking all windows confirms no length-4 run stays within the budget of 6.
Tap to reveal solution
Hardheap#632

Smallest Price Range Covering a Quote From Every Venue

Given K venues' sorted lists of distinct quoted prices seen during the day (each list sorted ascending), find the smallest price range [lo, hi] such that it contains at least one price from EVERY venue's list. This bounds how wide a price band you'd need to treat as 'the same price' across a fragmented, multi-venue market at any instant.

Input:
venues = [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output:
[20, 24]
Picking 24 from venue A, 20 from venue B, and 22 from venue C gives the window [20,24], width 4; the heap-based scan proves no narrower window touches all three venues.
Tap to reveal solution
Mediumdesign

Design: Position Size and Weighted-Average Cost Basis Tracker

Design a PositionTracker supporting buy(qty, price) and sell(qty, price), which may only sell up to the currently held quantity. Track the current position size, the weighted-average cost basis of the open position, and the cumulative REALIZED P&L across all sells so far.

Input:
buy(10, 100); buy(10, 120); sell(5, 150); position(); avg_cost(); realized_pnl()
Output:
15, 110.0, 200.0
After the two buys: 20 shares at a quantity-weighted average cost of (10*100 + 10*120)/20 = 110. Selling 5 shares at 150 realizes (150-110)*5 = 200 of P&L and leaves 15 shares still held at the same 110 average cost, since a sell never changes the average cost of what remains.
Tap to reveal solution
Mediumdesignheaphash-map

Design a Level-2 Order Book Supporting Best Bid/Ask and Cancel in Amortized O(log n)

Design a class OrderBook supporting add_order(order_id, side, price, qty), which adds a resting limit order on the given side ('buy' or 'sell'); cancel_order(order_id), which removes a previously added order; and best_bid() / best_ask(), which return the highest resting buy price / lowest resting sell price, or None if that side is currently empty.

Input:
add_order(1,"buy",100,10); add_order(2,"buy",101,5); cancel_order(2); best_bid()
Output:
100.0
Order 2, the higher-priced bid at 101, is cancelled before best_bid() is called, so the correct answer falls back to order 1's price of 100, even though order 2's stale entry may still physically sit in the underlying heap.
Tap to reveal solution
Mediumsliding-windowhash-table

Minimum Window Containing a Full Basket of Required Tickers

Given a chronological list of trade tickers (one ticker per trade, in time order) and a required basket of distinct tickers, return the length of the shortest contiguous run of trades that contains every ticker in the basket at least once. Return -1 if no such window exists.

Input:
trades=["AAPL","MSFT","AAPL","GOOG","MSFT"], basket={"AAPL","GOOG"}
Output:
2
The window [trades[2], trades[3]] = ["AAPL", "GOOG"] contains both required tickers and has length 2, shorter than the window starting at index 0.
Tap to reveal solution
Mediumheapintervalsgreedy

Minimum Monitoring Channels for Overlapping Trading Halts

You're given a list of trading halts across different symbols, each as [start, end] in minutes since market open. Each active halt needs one compliance monitor watching it live, and a monitor becomes free to reuse the instant its current halt ends. Return the minimum number of monitors needed to cover all halts.

Input:
halts=[[0,30],[5,10],[15,20]]
Output:
2
[0,30] is active the whole time, overlapping both [5,10] and [15,20], so a second monitor is needed while either of those is live. [5,10] and [15,20] never overlap each other, so they can share that second monitor.
Tap to reveal solution
Mediumprobabilitydynamic-programming

Probability of Filling at Least K of N VWAP Slices

An algo splits a parent order into N equal time slices and attempts to fill one child unit in each slice. Each slice independently fills with probability p, regardless of the others. Given N, p, and a required minimum number of filled slices k for the parent order to count as acceptably filled, compute the probability that at least k of the N slices fill.

Input:
N=3, p=0.5, k=2
Output:
0.5
P(at least 2 of 3 fill) = P(exactly 2) + P(exactly 3) = 3*(0.5^3) + 1*(0.5^3) = 0.375 + 0.125 = 0.5.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Days Until a Market-Regime Markov Chain Hits Risk-Off

A market is modeled as a finite-state Markov chain over daily regimes, with one or more absorbing (terminal) states such as a risk-off crash regime. Given the transition matrix, the set of absorbing state indices, and a starting state, return the expected number of days until the chain first reaches any absorbing state.

Input:
transition = [[0.6,0.3,0.1],[0.4,0.5,0.1],[0,0,1]], absorbing = [2], start = 0 // states: 0=Trending, 1=MeanReverting, 2=RiskOff
Output:
10.0
Solving E0 = 1 + 0.6*E0 + 0.3*E1 and E1 = 1 + 0.4*E0 + 0.5*E1 simultaneously gives E0 = E1 = 10.0 days -- plug back in to check: 1 + 0.6*10 + 0.3*10 = 10, and 1 + 0.4*10 + 0.5*10 = 10.
Tap to reveal solution
Mediumsliding-window

Shortest Run of Trading Days Hitting a Cumulative Volume Target

Given daily trading volumes for a stock as a list of positive integers volumes, and a target total target, return the length of the shortest contiguous run of days whose volumes sum to at least target. Return 0 if no such run exists.

Input:
volumes=[2,3,1,2,4,3], target=7
Output:
2
The run [4,3] at the end sums to 7 in just 2 days, which is shorter than any other run reaching at least 7 (e.g. [2,3,1,2] takes 4 days for the same target).
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Longest Clean-Tick Run After Deleting One Flagged Print

Your tick-cleaning pipeline flags each print as clean (1) or bad (0) in an array is_clean. You must delete exactly one tick from the series (even if the series is already all clean). Return the length of the longest contiguous run of clean ticks achievable after that single deletion.

Input:
is_clean=[1,1,0,1,1,1,0,1,1]
Output:
5
Delete the 0 at index 6: the run is_clean[3..8] minus that one bad tick leaves a contiguous clean run of length 5 (indices 3,4,5,7,8 collapse to one run once the bad tick between them is removed).
Tap to reveal solution
Hardheapsliding-window

Rolling Median Price for a Robust Volatility Gauge

Given a stream of prices and a fixed window size k, return the median of each window of k consecutive prices as the window slides one price at a time across the full series.

Input:
prices=[1,3,-1,-3,5,3,6,7], k=3
Output:
[1,-1,-1,3,5,6]
Window [1,3,-1] sorted is [-1,1,3], median 1. Window [3,-1,-3] sorted is [-3,-1,3], median -1. Each subsequent window drops the oldest price and admits the newest one before the median is read off again.
Tap to reveal solution
Harddynamic-programming

Max Profit With At Most K Transactions

Given daily prices for a stock and an integer k, you may complete at most k buy-then-sell transactions (never overlapping -- must sell before buying again). Return the maximum achievable profit.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3). Total 7, using both allowed transactions.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position Tracker With Realized P&L

Design a class tracking a single instrument's position that supports trade(qty, price), where qty is positive for a buy and negative for a sell. Buys and sells open cost-basis lots on their own side; an offsetting trade consumes the OLDEST opposite-side lots first (FIFO), realizing P&L against each lot's price as it's consumed, and any leftover trade quantity after all opposite-side lots are exhausted opens a new lot on the trade's own side. Support current_position() (net signed quantity) and realized_pnl() (cumulative realized P&L across all trades so far).

Input:
trade(100,10.0); trade(50,12.0); trade(-120,15.0); current_position(); realized_pnl()
Output:
30, 560.0
Buy 100@10 and buy 50@12 create two FIFO lots. Selling 120 consumes lot 1 (100 shares@10) entirely for 100*(15-10)=500 realized, then 20 shares from lot 2 (@12) for 20*(15-12)=60 realized, leaving 30 shares of lot 2 as the remaining long position. Net position = 30, cumulative realized P&L = 500 + 60 = 560.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Trading Window Under a Volume Budget

Given an array of daily non-negative trading volumes and an integer budget, return the length of the longest contiguous subarray of days whose total volume does not exceed budget.

Input:
volumes = [4, 2, 1, 7, 3], budget = 10
Output:
3
[4, 2, 1] sums to 7 (length 3) and [2, 1, 7] sums to 10 (length 3), both at or under budget. Extending either window past length 3 always pushes the sum over 10, so 3 is the longest window achievable.
Tap to reveal solution
Mediumsliding-window

Longest Window Where the High-Low Price Range Stays Within a Band

Given a sequence of intraday prices, find the length of the longest contiguous window where max(window) - min(window) <= band -- a volatility-band constraint used to flag calm vs choppy regimes.

Input:
prices=[5,6,5,4,8,3], band=2
Output:
4
The window [5,6,5,4] (indices 0-3) has max 6 and min 4, a range of exactly 2, so it fits the band. Extending to index 4 (price 8) pushes the range to 4, which breaks it, and no other window in the array reaches length 4 while staying within the band.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Trades and a Fixed Fee Per Trade

Given daily prices for one instrument, a maximum number of trades K (one trade = one buy followed by a later sell), and a fixed dollar fee charged per COMPLETED trade, return the maximum total profit achievable using at most K trades.

Input:
prices=[1,5,2,8,4,9], k=2, fee=1
Output:
10
Buy at 1, sell at 8 (profit 8-1-1=6), then buy at 4, sell at 9 (profit 9-4-1=4): total 10 using both trades. Selling at the local peak of 5 first is a trap -- holding through the dip to 2 and selling at 8 instead captures more with the same trade budget.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window With Bounded Price Range

Given an array of daily closing prices and a threshold limit, find the length of the longest contiguous run of trading days during which the price stayed within a band of width at most limit (max price in the window minus min price in the window <= limit).

Input:
prices=[8,2,4,7], limit=4
Output:
2
No window of length 3 or 4 has a max-min gap of 4 or less; [2,4] and [4,7] each have a gap of at most 3, so the best length is 2.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Minimum Window Reaching a Notional Target

Given a day's sequence of trade notionals (all positive), find the length of the shortest contiguous run of trades whose total notional is at least target. Return 0 if no such run exists. Do it in O(n).

Input:
notionals=[2,1,5,2,3,2], target=7
Output:
2
The window [5,2] sums to 7 in just 2 trades -- shorter than any other qualifying run.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position and Realized P&L Tracker

Design a single-symbol position tracker that supports trade(side, qty, price), recording a buy or sell fill, using FIFO lot matching -- a sell is matched against the oldest still-open buy lots first, and symmetrically a buy that closes a short matches the oldest open sell lots first. Support realized_pnl(), returning cumulative realized P&L so far, and position(), returning the current signed net quantity (positive = long, negative = short).

Input:
trade('buy',10,100); trade('buy',5,110); trade('sell',12,105); realized_pnl(); position()
Output:
40.0, 3
The sell for 12 first fully closes the oldest lot (10 @ 100): (105-100)*10 = 50. The remaining 2 units close 2 of the second lot (5 @ 110): (105-110)*2 = -10. Total realized P&L = 50 - 10 = 40. The second lot's leftover 3 shares @ 110 stay open, so position() is 3.
Tap to reveal solution
Easysliding-window

Maximum Average Notional Over Any Fixed K-Minute Window

Given an array of per-minute traded notional and an integer k, return the maximum average notional over any contiguous window of exactly k minutes.

Input:
notional=[40, 90, 20, 70, 60], k=2
Output:
65.0
Every 2-minute window's sum: [40,90]=130, [90,20]=110, [20,70]=90, [70,60]=130. The max sum is 130 (two windows tie for it), so the max average is 130/2 = 65.0.
Tap to reveal solution
Mediumheap

K Trade Prints Closest to a Reference Price

Given an array of trade prices and a reference price target, return the k prices closest to target, sorted ascending. When two prices are equally close to target, treat the smaller price as the closer one.

Input:
prices = [1,2,3,4,5], target = 3, k = 2
Output:
[2, 3]
Price 3 has distance 0, the closest. Prices 2 and 4 both have distance 1, but 2 is the smaller of the tied pair, so it's preferred as the second closest over 4.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Transactions and a Per-Trade Fee

Given daily prices, an integer k (the max number of buy-sell round trips allowed), and a fixed fee charged on every sell, find the maximum total profit. You can't hold more than one share at a time, and each of the k allowed round trips pays the fee once, on the sell.

Input:
prices=[3,2,6,5,0,3], k=2, fee=1
Output:
5
Buy at 2, sell at 6: profit 6-2-1=3. Buy at 0, sell at 3: profit 3-0-1=2. Total 3+2=5, using both allowed round trips.
Tap to reveal solution
Mediumdynamic-programming#309

Maximum Profit With a Mandatory One-Day Cooldown After Selling

Given daily prices, you may buy and sell as many times as you like, never holding more than one share at once, but after selling you must wait one full day before buying again (a cooldown, as if a wash-sale-style rule applied). Return the maximum achievable profit.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy at 1, sell at 2 (profit 1), skip a day for cooldown, buy at 0, sell at 2 (profit 2). Total profit 1 + 2 = 3, which beats any schedule that tries to trade through the cooldown.
Tap to reveal solution
Mediumsliding-window

Longest Contiguous Trading Window With At Most K Distinct Symbols

Given an array of symbol tickers representing a chronological stream of trades (one ticker per trade) and an integer k, return the length of the longest contiguous subarray containing at most k distinct tickers.

Input:
trades = ["AAPL","MSFT","AAPL","GOOG","MSFT"], k = 2
Output:
3
The window ["AAPL","MSFT","AAPL"] (indices 0-2) contains only 2 distinct tickers and has length 3. Extending to index 3 introduces "GOOG", a third distinct ticker, which violates k = 2, so no longer window qualifies.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Absorption Probability for an Asymmetric Inventory Walk

A market maker's inventory moves by +1 with probability p and -1 with probability 1-p on every tick, starting at some inventory between -N and N, with absorbing bounds at -N (breach short limit) and +N (breach long limit). Given N, p, and a starting inventory, return the probability the walk is absorbed at the UPPER bound +N (rather than the lower bound -N).

Input:
N = 3, p = 0.55, start = 0
Output:
0.5847
A slight upward drift (p > 0.5) makes absorption at the upper bound more likely than the 0.5 you'd get at p = 0.5 by symmetry, but the edge isn't overwhelming at this drift and distance.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Trailing Stop Trigger (Sliding Window Maximum)

Given daily closing prices, a lookback window W, and a stop percentage pct, determine for each day whether a trailing stop fires: price[i] <= (max price in the trailing W-day window ending at i) * (1 - pct). Return the indices where it fires. Do it in O(n) total, not O(n*W).

Input:
prices=[10,12,11,9,8,13], window=3, pct=0.2
Output:
[3]
At i=3 the trailing window is [12,11,9]; window high 12, stop level 9.6; price 9 <= 9.6 fires. Day 4 (price 8) does not re-fire under this rule since only the crossing day is reported.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Sliding Window Maximum Bid-Ask Spread (Monotonic Deque)

Given a sequence of bid-ask spreads observed at each tick and a window size w, return the maximum spread within every window of w consecutive ticks, for all such windows in order. You need every window's max, not just one, so it must run faster than recomputing the max from scratch for each window.

Input:
spreads=[0.02, 0.05, 0.01, 0.04, 0.03], w=3
Output:
[0.05, 0.05, 0.04]
Windows [0.02,0.05,0.01] -> 0.05, [0.05,0.01,0.04] -> 0.05, [0.01,0.04,0.03] -> 0.04.
Tap to reveal solution
Harddynamic-programming

Maximum Profit With a Mandatory Cooldown After Closing a Position

Given a sequence of daily prices for one instrument, return the maximum total profit from any number of non-overlapping round-trip trades, where you must wait at least one full day after selling before you're allowed to buy again.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy at 1 (index 0), sell at 2 (index 1): profit 1. Day 2 is a mandatory cooldown (can't buy at 3). Buy at 0 (index 3), sell at 2 (index 4): profit 2. Total profit 3, which beats any other sequence of trades respecting the cooldown.
Tap to reveal solution
Mediumprobabilitydynamic-programming

Probability of At Least K Up-Days in N Independent Trading Days

A stock closes up on any given day with independent probability p, and down otherwise. Given n trading days and a threshold k, return the probability of at least k up-days over the n days.

Input:
n=5, p=0.6, k=3
Output:
0.6826
Number of up-days follows Binomial(5, 0.6). P(X=3)+P(X=4)+P(X=5) = 0.3456 + 0.2592 + 0.07776 = 0.68256, which rounds to 0.6826.
Tap to reveal solution
Mediumdesignqueuehash-map

Design a FIFO-Lot Position Tracker for Realized P&L on Partial Sells

Design a class PositionTracker supporting buy(symbol, qty, price), which opens a new lot in that symbol's FIFO queue of open lots, and sell(symbol, qty, price), which closes the sold quantity against the OLDEST open lots first, partially consuming a lot if needed, and returns the realized P&L from that sell. Assume a sell's quantity never exceeds the symbol's total currently-open quantity.

Input:
buy("AAPL",100,10); buy("AAPL",50,12); sell("AAPL",120,15)
Output:
realized_pnl = 560.0
FIFO consumes the oldest lot first: 100 shares @10 fully (profit 100*(15-10)=500), then 20 of the 50 shares @12 (profit 20*(15-12)=60). Total 560. The remaining open lot is 30 shares @12.
Tap to reveal solution
Harddynamic-programming

Max Profit From a Single Instrument With At Most K Round-Trip Transactions

Given a sequence of daily prices for one instrument and an integer k, you may complete at most k buy-then-sell round trips (you must sell before you can buy again), and you must be fully flat between trips. Return the maximum total profit.

Input:
prices = [3,2,6,5,0,3], k = 2
Output:
7
Buy at 2, sell at 6 (profit 4). Buy at 0, sell at 3 (profit 3). Total 7, using exactly 2 of the allowed transactions and no more profit is reachable with up to 2 round trips.
Tap to reveal solution
Harddesignheaphash-map

Design a Price-Time-Priority Limit Order Book Matching Engine

Design a class OrderBook with add_order(order_id, side, price, qty), which matches the incoming order against resting opposite-side orders that cross its price, in price-time priority, and returns the resulting fills; and cancel_order(order_id), which removes a resting order. Partial fills must preserve a resting order's original time priority.

Input:
add_order(1,'sell',101.0,100); add_order(2,'buy',100.0,50); add_order(3,'buy',102.0,30)
Output:
first two calls return []; the third returns [(3, 1, 30, 101.0)]
Order 2's bid of 100.0 doesn't cross order 1's ask of 101.0, so it rests. Order 3's bid of 102.0 does cross, filling 30 shares at the RESTING order's price of 101.0 (price-time priority: the resting order's price wins, not the aggressor's).
Tap to reveal solution
Harddynamic-programming

Best Time to Buy and Sell Stock With At Most Two Transactions and a Per-Trade Fee

Given daily prices for a stock and a flat per-trade fee, where a 'trade' is one full buy-then-sell round trip, return the maximum profit achievable using at most two non-overlapping transactions (never holding more than one share at a time), where each completed transaction's profit is reduced by the fee.

Input:
prices=[1,5,3,8], fee=1
Output:
7
Two transactions: buy at 1, sell at 5 (profit 4, net 3 after the fee), then buy at 3, sell at 8 (profit 5, net 4 after the fee), for a total net profit of 7 -- better than one single transaction buying at 1 and selling at 8 (profit 7, net 6 after just one fee).
Tap to reveal solution
Hardprobabilitymarkov-chain

Probability a Market Maker's Inventory Random Walk Hits the Long Limit Before the Flat/Short Limit

A market maker's inventory starts at s shares, with 0 < s < N, and each tick moves to s + 1 with probability p or s - 1 with probability 1 - p, until it is absorbed at either 0 (forced flat) or N (the hard long risk limit). Given p, N, and s, return the probability the inventory reaches N before it reaches 0.

Input:
p = 0.5, N = 10, s = 4
Output:
0.4
With an unbiased (p = 0.5) random walk, the ruin probability reduces to the simple ratio of the starting distance from the lower barrier to the total distance between barriers: s / N = 4 / 10 = 0.4.
Input:
p = 0.5, N = 4, s = 1
Output:
0.25
Again s / N, since p = 0.5: 1 / 4 = 0.25.
Tap to reveal solution
Mediumdesignheap

Design a Top-of-Book Tracker (Best Bid/Ask) With Lazy-Deleted Heaps

Design a class TopOfBook supporting add_order(side, price, order_id), cancel_order(order_id), best_bid(), and best_ask(), each running in amortized O(log n) time.

Input:
t=TopOfBook(); t.add_order('bid',99.50,1); t.add_order('bid',99.75,2); t.add_order('ask',100.25,3); t.best_bid(); t.cancel_order(2); t.best_bid()
Output:
99.75, then 99.50
With orders 1 and 2 both resting bids, the best bid is the higher price, 99.75 (order 2). Cancelling order 2 leaves order 1's 99.50 as the new best bid.
Tap to reveal solution
Mediumheap#295

Running Median Trade Price From a Live Stream (Two-Heap Median Finder)

You receive a live stream of trade prices, one at a time. After each new trade arrives, report the median of every trade price seen so far.

Input:
trades = [5, 2, 8, 1]
Output:
[5.0, 3.5, 5.0, 3.5]
After [5]: median 5.0. After [5,2]: median (2+5)/2=3.5. After [5,2,8]: sorted [2,5,8], median 5.0. After [5,2,8,1]: sorted [1,2,5,8], median (2+5)/2=3.5.
Tap to reveal solution
Harddynamic-programming

Maximum Stock Profit with Both a Cooldown and a Transaction Fee

Given daily stock prices, unlimited transactions are allowed, but after selling you must wait one full day before buying again (cooldown), and every completed round trip costs a fixed transaction fee. Find the maximum achievable total profit.

Input:
prices=[1,4,2,9], fee=1
Output:
7
Buying on day 0 at 1 and holding all the way to sell on day 3 at 9 nets 9 - 1 - 1 (fee) = 7. Trying to also trade the dip on day 2 doesn't help: selling on day 1 at 4 triggers the cooldown, blocking a buy on day 2, and any alternative combination nets less than holding through to 9.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit With a Per-Trade Transaction Fee

Given daily prices for one instrument and a flat fee charged once per completed round-trip (buy then sell), return the maximum total profit from any number of non-overlapping trades, where each completed round-trip pays the fee exactly once.

Input:
prices = [1, 3, 2, 8, 4, 9], fee = 2
Output:
8
Buy at 1, sell at 8 (profit 7, minus fee 2 = 5); buy at 4, sell at 9 (profit 5, minus fee 2 = 3). Total 5+3=8, which beats any other combination of round-trips once the fee is accounted for.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With a Mandatory Settlement Cooldown

Given daily prices, you may buy and sell as many times as you like (one share at a time, no overlapping positions), but after selling you must wait one full day before you're allowed to buy again (a T+1 settlement cooldown). Return the maximum achievable profit.

Input:
prices=[1,2,3,0,2]
Output:
3
Buy day0 (price 1), sell day1 (price 2, profit 1), cooldown day2, buy day3 (price 0), sell day4 (price 2, profit 2). Total 1+2=3.
Tap to reveal solution
Mediumsliding-window

Maximum High-Low Range in Any Window of Size K

Given an array of daily closing prices and a window length k, return the largest value of (max price - min price) over any contiguous window of exactly k consecutive days.

Input:
prices = [10, 12, 8, 15, 9, 11], k = 3
Output:
7
The window [8, 15, 9] (indices 2-4) has max 15 and min 8, a range of 7, which is larger than any other window of length 3.
Tap to reveal solution
Mediumprobabilitydynamic-programming

Probability a Sequence of N Independent +1/-1 Trades Ends Net Positive

A trader makes n independent trades, each winning +1 with probability p or losing -1 with probability 1-p. Return the probability that the trader's cumulative P&L after all n trades is strictly positive (greater than 0).

Input:
n = 3, p = 0.5
Output:
0.5
With 3 fair coin-flip trades, the net P&L is odd, so it is never exactly 0 -- by symmetry, P(net > 0) equals P(net < 0), and together they must sum to 1, giving exactly 0.5 each.
Input:
n = 2, p = 0.6
Output:
0.36
Net P&L is positive only if both trades win: 0.6 * 0.6 = 0.36. Splitting one win and one loss nets to exactly 0, which does not count as strictly positive.
Tap to reveal solution
Harddesignheap

Design an Order Book Supporting Cancel and Amend-Quantity via Lazy Heap Deletion

Design a class OrderBook supporting add_order(order_id, side, price, qty), cancel_order(order_id), amend_quantity(order_id, new_qty), best_bid(), and best_ask(). best_bid/best_ask return the (price, qty) of the best resting order on that side, skipping any order that has since been cancelled or amended down to zero quantity, or None if the side is empty.

Input:
add_order('b1','buy',100.00,500); add_order('b2','buy',100.05,300); add_order('a1','sell',100.10,400); best_bid(); best_ask(); cancel_order('b2'); best_bid()
Output:
(100.05, 300); (100.10, 400); (100.00, 500)
b2 is initially the best bid at 100.05. After it's cancelled, the heap entry for b2 is skipped lazily and b1 at 100.00 becomes the reported best bid.
Tap to reveal solution
Hardtwo-pointersarraystack#42

Trapping Rain Water (Two Pointers)

Given n non-negative integers representing the heights of bars in an elevation map, compute how much water can be trapped after raining.

Input:
height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output:
6
Tap to reveal solution
Mediumheapdesign

Streaming Median of a Live Price Feed

Design a class that ingests a stream of trade prices one at a time via add(price) and can report the median of every price seen so far via median() at any point, with add running in O(log n) and median in O(1).

Input:
add(5); add(2); median(); add(8); median()
Output:
3.5, 5.0
After [5, 2] the sorted values are [2, 5], median 3.5. After adding 8 the sorted values are [2, 5, 8], median 5.0.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Expected Number of Ticks Until a Bounded Inventory Walk Gets Absorbed

A market maker's inventory moves by +1 with probability p and -1 with probability 1-p each tick, starting at some inventory strictly between -N and N, with absorbing bounds at -N and +N (either limit breach halts trading). Given N, p, and a starting inventory, return the expected number of ticks until the walk is absorbed at EITHER bound.

Input:
N = 3, p = 0.5, start = 0
Output:
9.0
For a symmetric simple random walk with absorbing barriers at -N and +N, the expected absorption time starting from the center is the classic result N^2 -- here 3^2 = 9.
Tap to reveal solution
Mediumprobability

Expected Number of Sign Changes in N Days of IID Coin-Flip Returns

A signal's daily return sign is modeled as an IID coin flip: +1 (up) with probability p, -1 (down) with probability 1-p, independent across days. Given N days and p, compute the expected number of sign changes (a day whose sign differs from the immediately preceding day) over the whole sequence in closed form -- no simulation required.

Input:
n_days=5, p=0.5
Output:
2.0
4 adjacent day-pairs, each independently flipping sign with probability 2*0.5*0.5 = 0.5, so 4 * 0.5 = 2.0.
Input:
n_days=10, p=0.6
Output:
4.32
9 adjacent pairs, each flipping with probability 2*0.6*0.4 = 0.48, so 9 * 0.48 = 4.32.
Tap to reveal solution
Hardheap

Smallest Price Range Covering a Quote From Every Venue

Given K venues, each providing its own sorted (ascending) list of quoted prices, return the smallest price range [low, high] that includes at least one quote from every venue.

Input:
venues = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output:
[20, 24]
The range [20, 24] contains 24 from venue 1, 20 from venue 2, and 22 from venue 3 -- one quote from each venue, in a range of width 4, which is the smallest achievable.
Tap to reveal solution
Harddesignheap

Design: Level-1 Order Book (Best Bid/Ask With Cancel)

Design an OrderBook supporting add_bid(order_id, price), add_ask(order_id, price), cancel(order_id), best_bid(), and best_ask(). best_bid/best_ask must return the highest live bid price and lowest live ask price (or None if that side is empty).

Input:
add_bid(1, 100); add_bid(2, 102); add_ask(3, 105); best_bid(); best_ask(); cancel(2); best_bid()
Output:
102, 105, 100
After the first three orders, the best bid is the higher of 100 and 102 (102), and the best ask is 105. Cancelling order 2 (the 102 bid) drops the best bid back down to 100.
Tap to reveal solution
Harddynamic-programming

Best Time to Buy and Sell Stock With At Most K Transactions

Given daily prices and an integer k, you may complete at most k non-overlapping buy-then-sell round trips (you must sell before buying again, and cannot hold more than one share at a time). Return the maximum achievable profit.

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy day1 (2), sell day2 (6): profit 4. Buy day4 (0), sell day5 (3): profit 3. Total 4+3=7, using both allowed transactions.
Tap to reveal solution
Hardheap#295

Running Median of a Live Trade Print Stream Using Two Heaps

Design a class that processes a live stream of trade prices one at a time via add_price(price), and at any point can return the median of all prices seen so far via get_median().

Input:
add_price(10); add_price(20); get_median(); add_price(15); get_median()
Output:
15.0; then 15.0
After [10, 20] the median of the two middle values is (10+20)/2 = 15.0. After inserting 15, the sorted stream is [10, 15, 20] and the median is the single middle element, 15.0.
Tap to reveal solution
Hardsliding-windowmonotonic-dequeprefix-sum

Shortest Consecutive-Day Window With Net Order Flow At Least K

Given an array of daily net order flow (positive means net buying, negative means net selling -- any integer, can be negative) and a target K, find the length of the shortest contiguous run of days whose net order flow sums to at least K. Return -1 if no such window exists.

Input:
flow=[2,-1,2], K=3
Output:
3
The only window summing to at least 3 is the whole array; every shorter window falls short because of the -1 day in between.
Input:
flow=[1,2], K=4
Output:
-1
The best possible sum, using both days, is only 3.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit With a Mandatory Cooldown Day After Each Sale

Given daily prices for a stock, return the maximum profit achievable with unlimited buy/sell transactions (never holding more than one share at a time), given that after selling you cannot buy again on the very next day (one mandatory cooldown day).

Input:
prices=[1,2,3,0,2]
Output:
3
Buy at index 0 (price 1), sell at index 1 (price 2) for profit 1, cooldown on index 2 (forced, can't buy the day right after selling), then buy at index 3 (price 0), sell at index 4 (price 2) for profit 2. Total profit 1 + 2 = 3, which beats the alternative of buying at 1 and selling at 3 for a single profit of 2.
Tap to reveal solution
Harddynamic-programming#188

Max Profit With At Most K Buy-Sell Transactions

Given a daily price array and an integer k, you may complete at most k buy-then-sell transactions (each sell must happen before the next buy; no holding more than one share at a time). Return the maximum achievable profit.

Input:
prices = [3,2,6,5,0,3], k = 2
Output:
7
Buy at 2, sell at 6 (profit 4), then buy at 0, sell at 3 (profit 3), for a total of 7 using exactly 2 of the allowed transactions.
Tap to reveal solution
Hardprobabilitymatrix-exponentiationmarkov-chain

Credit Rating Migration: Probability of Default Within N Years

Given a one-year credit rating transition matrix (rows are the current rating, columns the next year's rating, each row summing to 1, with Default as an absorbing state), a starting rating, and a horizon of N years, return the probability of having transitioned into Default at or before the end of year N.

Input:
P=[[0.90,0.08,0.02],[0.10,0.80,0.10],[0.00,0.00,1.00]] (order A,B,Default), start=A, n_years=2
Output:
0.046
P squared gives the two-year transition matrix directly; entry (A, Default) of P^2 is 0.9*0.02 + 0.08*0.10 + 0.02*1.00 = 0.018 + 0.008 + 0.02 = 0.046, the probability of reaching Default by year 2 starting from A.
Tap to reveal solution
Mediumprobabilitymarkov-chain

Probability of a Margin Call Before Recovery in an Absorbing Markov Chain

A position's collateral level moves between discrete states 0..N each day, transitioning according to a given N+1 by N+1 transition matrix. State 0 is 'margin called' (absorbing) and state N is 'fully recovered / desk closes the watch' (absorbing). Given the matrix and a starting state s, compute the probability of eventually being margin-called (hitting state 0) rather than recovering (hitting state N).

Input:
N=3, P=[[1,0,0,0],[0.3,0.2,0.4,0.1],[0.1,0.3,0.2,0.4],[0,0,0,1]], s=1
Output:
approximately 0.538
States 0 and 3 are absorbing; states 1 and 2 are transient. Starting in state 1, solve the linear system for absorption probabilities into state 0.
Tap to reveal solution
Hardprobabilitydynamic-programming

Probability a Symmetric Random Walk Returns to Zero

A fair coin drives a random walk starting at 0: each step moves +1 or -1 with equal probability. Given n steps, compute the probability that the walk visits position 0 at least once at some point during steps 1 through n (touching 0 counts even if it moves away again afterward).

Input:
n=4
Output:
0.625
Of the 16 equally likely 4-step paths, 10 touch 0 at some point (e.g. +--+ reaches 0 after 2 steps and stays counted even though it moves to +1 and back to 0 again). 10/16 = 0.625.
Tap to reveal solution
Mediumsliding-windowdeque

Streaming VWAP Over the Last K Trades

Given a stream of trades, each with a price and a size, maintain the volume-weighted average price (VWAP) over the most recent K trades as new trades arrive. Return the running list of VWAP values, one per trade once at least one trade has arrived.

Input:
trades=[(100,10),(102,5),(98,20),(101,5)], k=3
Output:
[100.0, 100.67, 99.14, 99.62]
After the 4th trade, the window holds the last 3 trades (102,5),(98,20),(101,5): VWAP = (102*5+98*20+101*5)/(5+20+5) = 99.615...
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Lot-Matched Position Tracker With Realized P&L

Design a class tracking a single instrument's position using FIFO (first-in-first-out) lot matching: buy(quantity, price) adds a new lot; sell(quantity, price) closes quantity against the OLDEST open lots first, and returns the realized P&L from that sell (splitting a lot if the sell quantity doesn't align exactly with a lot's remaining size). Also support net_position() returning the current share count.

Input:
buy(100, 10.0); buy(50, 12.0); sell(120, 15.0)
Output:
sell returns 560.0
The sell of 120 shares closes the full first lot (100 @ 10.0, profit 100*(15-10)=500) plus 20 of the second lot (20 @ 12.0, profit 20*(15-12)=60) -- FIFO uses the oldest lot first and only touches the second lot for the remaining 20 shares -- for a total realized P&L of 500+60=560.
Tap to reveal solution
Mediumdynamic-programming

Maximum Profit With Unlimited Transactions and a Flat Fee Per Trade

Given daily prices and a flat fee charged once per completed round trip, you may hold at most one share at a time with unlimited transactions. Return the maximum achievable profit.

Input:
prices=[1,3,2,8,4,9], fee=2
Output:
8
Buy at 1, sell at 8 (profit 7 minus fee 2 = 5), then buy at 4, sell at 9 (profit 5 minus fee 2 = 3). Total 5+3=8, better than any other split of trades.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Lot-Matching Position and Realized P&L Tracker

Design a single-instrument position tracker that supports buy(qty, price) to open or add to a long position, and sell(qty, price) to close part or all of it. Sells must match against the OLDEST open lots first (FIFO), and each sell should return the realized P&L generated by that sell, computed lot by lot against the price each matched lot was originally bought at. Assume sells never exceed the current long position.

Input:
buy(10, 100); buy(5, 105); sell(12, 110)
Output:
realized_pnl=110.0, remaining_lots=[(105, 3)]
The sell of 12 first closes the oldest lot (10 @ 100) for (110-100)*10=100 realized, then closes 2 of the 5 units from the next lot (@ 105) for (110-105)*2=10 realized, totaling 110. The remaining 3 units of that second lot stay open at cost basis 105.
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With a Transaction Fee

Given daily prices and a fixed fee charged once per completed round trip, you may complete as many non-overlapping buy-then-sell transactions as you like (sell before buying again, hold at most one share at a time). Return the maximum achievable profit after fees.

Input:
prices=[1, 3, 2, 8, 4, 9], fee=2
Output:
8
Buy at 1, sell at 8: profit 7 minus fee 2 = 5. Buy at 4, sell at 9: profit 5 minus fee 2 = 3. Total 5+3=8, better than any single round trip alone.
Tap to reveal solution
Harddynamic-programming#188

Maximum Profit With At Most K Buy-Sell Transactions

Given daily prices and an integer k, you may complete at most k buy-then-sell round trips (never holding more than one share at once, and a sell must happen before the next buy). Return the maximum achievable profit.

Input:
k = 2, prices = [3, 2, 6, 5, 0, 3]
Output:
7
Buy at 2, sell at 6 (profit 4); buy at 0, sell at 3 (profit 3). Two transactions, total profit 4 + 3 = 7 -- the best achievable with at most 2 round trips.
Tap to reveal solution
Mediumdesign

Design a Fixed-Window VWAP Tracker With O(1) Updates

Design a class VWAPTracker, constructed as VWAPTracker(window_size), that supports add_trade(price, size), ingesting one trade at a time, and vwap(), returning the volume-weighted average price over the last window_size trades (a fixed COUNT window, not a time window), each in O(1) amortized time.

Input:
t=VWAPTracker(3); t.add_trade(10,100); t.add_trade(20,100); t.add_trade(30,100); t.vwap(); t.add_trade(40,100); t.vwap()
Output:
20.0, then 30.0
After the first three trades, vwap = (10*100+20*100+30*100)/(100+100+100) = 6000/300 = 20.0. Adding (40,100) evicts the oldest trade (10,100) from the window, leaving (20,100),(30,100),(40,100): vwap = 9000/300 = 30.0.
Tap to reveal solution
Mediumsliding-window#209

Shortest Tick Window to Accumulate At Least a Target Volume

Given a sequence of per-tick traded volumes and a target volume V, return the length of the shortest contiguous window of ticks whose volumes sum to at least V, or 0 if no such window exists. This estimates how many ticks a TWAP execution slice needs to watch before enough real market volume has printed to safely trade against it.

Input:
volumes = [2, 1, 5, 3, 2], V = 7
Output:
2
The window [5, 3] sums to 8 >= 7 with length 2, and no window of length 1 reaches 7, so 2 is the shortest qualifying window.
Tap to reveal solution
Hardsliding-windowmonotonic-deque

Longest Trading Window Where Price Stays Within a Volatility Band

Given a sequence of intraday prices and a band width w, find the length of the longest contiguous window where the difference between the maximum and minimum price in that window never exceeds w -- the longest stretch a mean-reversion strategy could safely treat as range-bound.

Input:
prices=[10,1,2,4,7,2], w=5
Output:
4
The window [2,4,7,2] (indices 2-5) has max 7 and min 2, a range of 5, which fits the band -- no longer window satisfies the constraint.
Tap to reveal solution
Mediumheap

K Trade Prices Closest to a Reference Price

Given a list of trade prices printed during a session, a reference price (e.g. the prior close or a fair-value estimate), and an integer k, return the k trade prices closest to the reference price -- without fully sorting the entire trade list.

Input:
prices=[102,94,101,105,89], ref=100, k=3
Output:
[101, 102, 105]
Distances from 100 are 2, 6, 1, 5, 11 respectively. The 3 smallest distances belong to 101 (1), 102 (2), and 105 (5).
Tap to reveal solution
Harddesignheaporder-book

Design a Price-Time-Priority Limit Order Book Matching Engine

Design a class OrderBook with add_limit_order(order_id, side, price, qty) that rests a limit order ('buy' or 'sell') in the book, and match_market_order(side, qty) that fills an incoming market order against the OPPOSITE side's resting orders using price-time priority: best price first, and for equal prices, the order that was added earliest. match_market_order should return the list of (order_id, filled_qty, price) fills, plus any quantity left unfilled if the book runs dry.

Input:
add_limit_order("A1","sell",101.0,100); add_limit_order("A2","sell",100.5,50); add_limit_order("A3","sell",100.5,30); match_market_order("buy", 70)
Output:
fills=[("A2",50,100.5),("A3",20,100.5)], unfilled=0
A2 and A3 both rest at the best ask price 100.5, so price-time priority fills A2 first (added earlier) for its full 50, then A3 for the remaining 20 needed -- A1's worse price at 101.0 is never touched.
Tap to reveal solution
Hardprobabilitymarkov-chain

Expected Time to Default in a Credit Rating Markov Chain

A bond issuer's credit rating transitions each year between three states: Investment Grade (IG), High Yield (HY), and Default (an absorbing state -- once entered, it is never left). Given the one-year transition probabilities among the transient states, compute the expected number of years until default for an issuer currently in each of IG and HY.

Input:
Q (transient-to-transient) = {IG: {IG:0.90, HY:0.08}, HY: {IG:0.10, HY:0.75}} (remainder of each row goes to Default)
Output:
{IG: 19.41, HY: 11.76}
Solving t_IG = 1 + 0.90*t_IG + 0.08*t_HY and t_HY = 1 + 0.10*t_IG + 0.75*t_HY gives t_IG ~= 19.41 and t_HY ~= 11.76 -- HY defaults sooner on average despite occasionally upgrading, since its direct default probability each year is much higher.
Tap to reveal solution
Harddesignheap

Design a Price-Time-Priority Limit Order Matching Engine

Design a class OrderBook supporting add_order(side, price, qty), where side is 'buy' or 'sell'. Each new order first matches against resting orders on the opposite side at or better than its price, in price-time priority (best price first, then earliest order first), filling as much as possible; any unfilled remainder rests in the book. Return the list of fills produced by this call, each as (price, qty) at the price of the already-resting order.

Input:
add_order('sell', 101.0, 5); add_order('sell', 100.0, 3); add_order('buy', 101.0, 6)
Output:
[]; []; [(100.0, 3), (101.0, 3)]
The two sells rest with nothing to match against. The incoming buy at 101 matches the better-priced resting sell at 100 first (filling all 3), then the remaining 3 shares against the resting sell at 101, exhausting the buy order with no remainder left to rest.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window of Consecutive Prices With Range Under a Volatility Cap

Given a chronological array of prices and a cap, return the length of the longest contiguous window where (max price in the window - min price in the window) does not exceed cap. This is a coarse proxy for 'how long can I hold a position before its intrabar range trips a volatility limit.'

Input:
prices=[8,2,4,7], cap=3
Output:
2
Window [4,7] (range 3) and [2,4] (range 2) both qualify at length 2; no length-3 window keeps its range within 3 (e.g. [2,4,7] has range 5).
Tap to reveal solution
Hardsliding-windowhash-map

Minimum Window Containing At Least One Trade From Each Required Hedge Leg

Given a chronological array of trade tickers and a set of required hedge legs (tickers that must all appear at least once), find the length of the shortest contiguous window of trades that contains at least one trade from every required leg. Return -1 if no such window exists.

Input:
trades=['AAPL','MSFT','AAPL','GOOG','MSFT','AAPL'], required={'MSFT','GOOG'}
Output:
2
The window ['GOOG','MSFT'] (indices 3-4) contains one trade from each required leg (GOOG, MSFT) and has length 2 -- the shortest possible since both legs must appear at all.
Tap to reveal solution
Easyarraydynamic-programming#121

Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the i-th day. You want to maximize your profit by choosing a single day to buy one stock and a different day in the future to sell. Return the maximum profit, or 0 if no profit is possible.

Input:
prices = [7,1,5,3,6,4]
Output:
5
Buy at 1, sell at 6.
Input:
prices = [7,6,4,3,1]
Output:
0
Tap to reveal solution
Harddesignheap

Design a Price-Time Priority Limit Order Matching Engine

Design a class MatchingEngine with add_order(side, price, size, order_id), which immediately crosses the new order against resting orders on the opposite side at the RESTING order's price (price-time priority), partially filling as needed and resting any unfilled remainder; it returns the list of fills generated. Also support cancel_order(order_id).

Input:
e=MatchingEngine(); e.add_order('buy',100.0,10,1); e.add_order('sell',99.0,4,2)
Output:
[], then [(1, 2, 100.0, 4)]
Order 1 rests (nothing to cross). Order 2 is willing to sell at 99 or better; it crosses resting bid 1, trading at the RESTING order's price of 100.0 for the overlapping size of 4, leaving order 1 resting with size 6.
Tap to reveal solution
Hardheap

Smallest Price Range Covering a Print From Each of K Correlated Tickers

You have K correlated tickers, each with a sorted array of prices it printed during a matching calibration window (used to check a basket is trading in line). Find the smallest price range [lo, hi] such that at least one printed price from every ticker's array falls inside it.

Input:
prices=[[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output:
[20, 24]
The range 20 to 24 contains 24 from list 1, 20 from list 2, and 22 from list 3 -- one print from every ticker -- and no narrower range covers all three lists.
Tap to reveal solution
Mediumdesign

Design a Position Tracker With Average Cost Basis and Realized P&L on Partial Closes

Design a class PositionTracker supporting buy(qty, price), which adds to a long position using a volume-weighted average cost basis, and sell(qty, price), which reduces the position (never called with qty exceeding the current quantity) and returns the realized P&L from that sell, computed against the position's average cost basis at the time of the sell. Also support current_quantity() and average_cost() (returns None if flat).

Input:
buy(100, 10.0); buy(100, 12.0); sell(50, 15.0); average_cost(); current_quantity()
Output:
sell returns 200.0; average_cost() = 11.0; current_quantity() = 150
After both buys, 200 shares sit at a volume-weighted average cost of (100*10 + 100*12) / 200 = 11.0. Selling 50 shares at 15 realizes (15 - 11) * 50 = 200 in P&L. Selling never changes the average cost basis of the remaining shares, so it stays at 11.0 with 150 shares left.
Tap to reveal solution
Mediumdesign

Design: Position Tracker With Average Cost Basis and Realized P&L

Design a PositionTracker for one instrument supporting trade(quantity, price), where quantity is positive for a buy and negative for a sell (short sales allowed). The tracker maintains a running position and its average cost basis, and each call returns the REALIZED P&L produced by that specific trade (0 if the trade only adds to an existing position without closing any of it). A trade that closes the existing position and still has size left over must flip to the opposite side in the same call, with the leftover opening fresh at the trade's own price.

Input:
trade(10, 100); trade(5, 110); trade(-20, 120)
Output:
0.0, 0.0, 250.0
First trade opens 10 long @ 100, no realization. Second trade adds 5 more @ 110, blending the average cost to (10*100 + 5*110)/15 = 103.33, still no realization. Third trade sells 20: the first 15 close the long at a realized profit of (120 - 103.33) * 15 = 250.0, and the remaining 5 open a new short position @ 120.
Tap to reveal solution
Harddynamic-programming#188

Max Profit With At Most K Round-Trip Trades

Given a daily price array and an integer k, you may complete at most k buy-then-sell round trips (you must fully sell before buying again, and can hold at most one share at a time). Return the maximum achievable profit.

Input:
prices = [3,2,6,5,0,3], k = 2
Output:
7
Buy at 2, sell at 6, for a profit of 4. Then buy at 0, sell at 3, for a profit of 3. Total profit across the two allotted round trips is 7, which is optimal.
Tap to reveal solution
Harddesignheap

Design a Limit Order Book With Price-Time Priority

Design a class LimitOrderBook supporting add_order(order_id, side, price, size), which matches the incoming order against resting orders on the opposite side using price-time priority (best price first, ties broken by earliest arrival), partially or fully filling it and resting any unfilled remainder, and cancel(order_id), which removes an order's remaining resting quantity. Track all fills as (resting_order_id, incoming_order_id, price, size) tuples.

Input:
add_order(1,"SELL",101,50); add_order(2,"BUY",101,30); add_order(3,"BUY",102,40)
Output:
fills = [(1, 2, 101, 30), (1, 3, 101, 20)]
Order 2 fills 30 of order 1's resting 50 at 101. Order 3 then fills order 1's remaining 20 at 101 (price-time priority: the resting order fills before order 3 rests its own 20 remaining shares at 102).
Tap to reveal solution
Mediumsliding-windowfinance

Rolling VWAP (Volume-Weighted Average Price)

Given a stream of (price, volume) ticks and a window of N most-recent ticks, return the VWAP — sum(p*v) / sum(v) — after each tick.

Input:
window=3, ticks: (100,10), (101,5), (99,20), (102,15)
Output:
100.0, 100.33, 99.71, 100.97
Tap to reveal solution
Hardheaptwo-pointers

K Smallest Combined Costs Pairing Two Venue Quote Lists

You can hedge a position by pairing one quote from venue A's sorted ascending cost list with one quote from venue B's sorted ascending cost list; the combined cost of a pairing (i, j) is a[i] + b[j]. Return the k pairs with the smallest combined cost, without generating and sorting all len(a) * len(b) pairs.

Input:
a=[1,7,11], b=[2,4,6], k=3
Output:
[(1,2), (1,4), (1,6)]
Pairing a[0]=1 against b's three smallest quotes beats every pairing that uses a[1]=7 or a[2]=11, since a is sorted and 1 is its minimum -- those three dominate the k=3 smallest sums here.
Tap to reveal solution
Harddesignqueue

Design an Iceberg Order Matching Engine

Design a class IcebergBook, scoped to a single resting side at a single price, supporting add_iceberg(order_id, display_size, total_size), which rests an order that only ever shows display_size shares at a time (the rest stays hidden), and add_market_order(size), which matches an incoming market order against the resting queue in arrival order, filling only the currently VISIBLE size of the order at the front. Whenever a resting order's visible clip is fully consumed, replenish it with a fresh clip from its hidden remainder (display_size, or whatever hidden amount is left if smaller) and send it to the BACK of the queue, losing its time priority -- the standard convention for iceberg replenishment. Return the list of (order_id, fill_size) fills produced by one market order call.

Input:
add_iceberg(1, display_size=10, total_size=25); add_iceberg(2, display_size=5, total_size=5); add_market_order(size=12)
Output:
[(1, 10), (2, 2)]
Order 1 shows 10; the market order takes all 10, exhausting the visible clip, so order 1 replenishes 10 more from its hidden 15 and moves to the BACK of the queue. Order 2 is now at the front showing 5; the remaining 2 shares of the market order fill against it.
Tap to reveal solution
Mediumsliding-windowmonotonic-deque

Longest Window Where the Price Stays Within a Volatility Band

Given an array of daily prices and a band width limit, return the length of the longest contiguous window where max(window) - min(window) <= limit.

Input:
prices=[8,2,4,7], limit=4
Output:
2
[2,4] has range 2 (<=4). [4,7] has range 3 (<=4). Any 3-length window (e.g. [2,4,7], range 5, or [8,2,4], range 6) breaks the limit, so 2 is the longest valid window.
Tap to reveal solution
Mediumdesignhash-map

Design a Position Tracker With Average Cost Basis and Realized/Unrealized PnL

Design a class PositionTracker supporting trade(ticker, side, qty, price), which updates a running position using average-cost accounting, and unrealized_pnl(ticker, mark_price) / realized_pnl(ticker) queries. A trade against the current position realizes PnL on the overlapping quantity at the existing average cost; if the trade exceeds the current position, the excess opens a new position on the flipped side at the trade's own price.

Input:
trade('AAPL','buy',100,150.0); trade('AAPL','buy',100,160.0); trade('AAPL','sell',150,170.0)
Output:
realized_pnl('AAPL') = 2250.0, unrealized_pnl('AAPL', 170.0) = 750.0
The two buys average to a cost basis of 155.0 over 200 shares. Selling 150 of them realizes 150 * (170 - 155) = 2250 and leaves 50 shares still long at the same 155.0 cost basis, worth 50 * (170 - 155) = 750 unrealized.
Tap to reveal solution
Mediumsliding-windowhash-map

Smallest Contiguous Trading Window Covering Every Required Sector

Given a chronological list of single-stock trades, each tagged with a sector, and a set of required sectors that a compliance rule says must all appear at least once in a reporting window, find the length of the shortest contiguous window of trades that contains every required sector at least once. Return 0 if no such window exists.

Input:
trades=["Tech","Energy","Tech","Financials","Energy"], required={"Tech","Financials"}
Output:
3
The window ["Tech","Financials"] alone would need trades 2..3, but trade 1 (index 2, "Tech") through trade 3 (index 3, "Financials") is a window of length 2 -- wait, indices 2-3 are ["Tech","Financials"], length 2, which is in fact the true minimum; a length-3 window like indices 0-2 also contains both but is not minimal. The shortest valid window has length 2.
Tap to reveal solution
Mediumheapdesign

Design a Streaming Median Tracker for Trade Prices

Design a data structure that processes a live stream of trade prices one at a time via add(price), and supports median() to return the current median of every price seen so far. Both operations need to stay efficient as the stream grows -- you should not resort the entire history on every median() call.

Input:
add(5); add(2); add(8); median(); add(1); median()
Output:
5, then 3.5
After 5, 2, 8: sorted [2,5,8], median is the middle value 5. After adding 1: sorted [1,2,5,8], median is the average of the two middle values (2+5)/2 = 3.5.
Tap to reveal solution
Hardprobabilitymarkov-chain

Probability a Market Maker's P&L Hits a Profit Target Before a Stop-Loss, Given an Asymmetric Win Rate

A market maker's cumulative P&L moves in discrete one-tick steps starting from 0: up one tick with probability p, down one tick with probability 1 - p, independently each step. Given p and two positive integers a (profit target, in ticks above 0) and b (stop-loss, in ticks below 0), compute the probability the P&L reaches +a before it reaches -b.

Input:
p = 0.5, a = 3, b = 2
Output:
0.4
With a fair coin, the probability of reaching the target first is simply the distance to the OTHER boundary over the total range: b / (a + b) = 2 / 5 = 0.4.
Tap to reveal solution
Harddesignheap

Design a Limit Order Book With Price-Time Priority Matching

Design a class OrderBook that supports add_buy_order(order_id, price, size) and add_sell_order(order_id, price, size), each of which should immediately match against resting orders on the OPPOSITE side at the best available price (price priority), breaking ties between orders at the same price by whichever arrived first (time priority), filling as much size as possible before resting any unfilled remainder on the book. Also support best_bid() and best_ask(), each returning the best resting price on that side, or None if that side is empty.

Input:
ob = OrderBook(); ob.add_sell_order(1, 101, 10); ob.add_sell_order(2, 100, 5); ob.add_buy_order(3, 101, 12)
Output:
Order 3 fills 5 @ 100 against order 2, then 7 @ 101 against order 1; order 1 rests with 3 remaining size at 101; best_ask() -> 101
Price priority means the incoming buy order matches the cheapest resting sell (100) first, even though it was quoted second, before moving on to the next-best price (101).
Tap to reveal solution
Mediumdynamic-programming

Max Profit With Unlimited Transactions and a One-Day Settlement Cooldown

Given daily prices, you may complete as many buy-sell transactions as you like, but after selling you must wait at least one full day before buying again (a T+1-style settlement cooldown) -- you may not buy on the day immediately after a sell. Return the maximum achievable profit.

Input:
prices = [1, 2, 3, 0, 2]
Output:
3
Buy day 0 at 1, sell day 1 at 2 for profit 1. Day 2 is a forced cooldown (no buying), but day 3 is free -- buy at 0, sell day 4 at 2 for profit 2. Total profit 1 + 2 = 3, which beats any pairing that tries to also use day 2's price of 3.
Tap to reveal solution
Mediumprobabilitymath

Fair Coin from a Biased Coin

Given a function biased() that returns 1 with unknown probability p (0 < p < 1) and 0 otherwise, implement fair() that returns 0 or 1 with exactly 50/50 probability.

Input:
1000 calls to fair() with p=0.7
Output:
~500/500 split
Tap to reveal solution
Mediumdynamic-programming

Best Time to Buy and Sell Stock With a One-Day Cooldown

Given daily prices, you may complete as many buy-then-sell transactions as you like (hold at most one share at a time, sell before buying again), but after selling you must wait one full day (a cooldown) before your next buy. Return the maximum achievable profit.

Input:
prices=[1, 2, 3, 0, 2]
Output:
3
Buy at 1 (day 0), sell at 2 (day 1) for profit 1, cooldown on day 2, buy at 0 (day 3), sell at 2 (day 4) for profit 2. Total profit 1+2=3 -- higher than a single round trip buying at 1 and selling at 3 (profit 2), because splitting into two trips banks the dip at 0.
Tap to reveal solution
Mediumprobabilitydynamic-programming

Gambler's Ruin: Probability of Reaching a Profit Target Before Going Bust

A trader starts with capital `start` and makes a sequence of unit-size bets, winning +1 with probability p and losing -1 with probability (1-p), stopping either at capital `target` (success) or capital `bust` (ruin). Return the probability of reaching `target` before `bust`.

Input:
start=5, target=10, bust=0, p=0.4
Output:
0.1215
With an unfavorable coin (p < 0.5), the probability of climbing from 5 to 10 before falling to 0 is well below the naive 5/10 = 0.5 you'd guess for a fair coin.
Tap to reveal solution
Mediumdesignsliding-windowqueue

Design a Sliding-Window Order Submission Rate Limiter

An exchange enforces a hard throttle: at most N orders may be submitted in any rolling T-millisecond window (not a fixed calendar window -- any T-millisecond span, sliding continuously). Design allow(timestamp) which is called once per prospective order submission and returns whether that order is allowed to go out under the current rolling window, given the timestamps of all previously allowed submissions.

Input:
N=3, T=1000; calls: allow(0), allow(200), allow(500), allow(900), allow(1100)
Output:
True, True, True, False, True
At allow(900), the trailing 1000ms window already contains 3 allowed submissions (0, 200, 500), so it is rejected; at allow(1100), timestamp 0 has fallen out of the trailing window, leaving room for a new submission.
Tap to reveal solution
Mediumsliding-window

Longest Trading Window Under a Rolling Notional Budget

Given a chronological array of trade notionals (can include negative values for sells) and a max_gross budget, find the length of the longest contiguous window of trades where the sum of absolute notionals traded in that window never exceeds max_gross at any point while the window is open.

Input:
notionals=[50,-30,20,-80,10], max_gross=100
Output:
3
Window [50,-30,20] has running |sum of abs values| = 50, 80, 100 -- fits exactly. Extending to include -80 pushes cumulative gross to 180, over budget, so the window must shrink from the left first.
Tap to reveal solution
Mediumdesignqueue

Design a FIFO Position Tracker With Realized P&L on Partial Sells

Design a class PositionTracker for a single symbol supporting buy(qty, price), which adds a new lot at that price, and sell(qty, price), which closes out quantity against the OLDEST open lots first (FIFO) and returns the realized P&L from this sell (using each consumed lot's own cost basis, not an average), raising an error if qty exceeds the currently open position.

Input:
buy(10,100); buy(10,110); sell(15,120)
Output:
250.0
FIFO consumes the first lot fully: 10 shares at (120-100)=20 profit each = 200. Then 5 shares from the second lot at (120-110)=10 profit each = 50. Total realized P&L = 200+50 = 250.0, leaving 5 shares of the second lot still open at cost 110.
Tap to reveal solution
Mediumheap

Running Median of a Live Trade Price Stream

Design a class MedianTracker with add(price) that ingests one trade price at a time from a live stream, and median() that returns the median of all prices seen so far in O(log n) for add and O(1) for median.

Input:
add(5); add(2); median(); add(8); median()
Output:
3.5, 5.0
After [5, 2], sorted is [2, 5], median of an even-sized set is the average of the two middle elements: (2+5)/2 = 3.5. After adding 8, sorted is [2, 5, 8], an odd-sized set whose median is the single middle element, 5.0.
Tap to reveal solution
Mediumdesignbinary-search

Design a Point-in-Time Price Cache With asof(timestamp) Lookups

Design a class PITPriceCache supporting record(timestamp, price), appending a new observation (timestamps arrive in non-decreasing order), and asof(query_timestamp), which returns the most recent recorded price at or before query_timestamp, or None if no such observation exists yet. This is the lookup primitive behind any point-in-time join: 'what did we know as of this moment.'

Input:
cache=PITPriceCache(); cache.record(10,100.0); cache.record(20,101.5); cache.record(35,99.0); cache.asof(25)
Output:
101.5
At query time 25, the most recent recorded observation at or before it is the one recorded at timestamp 20 (price 101.5); the one at 35 hasn't happened yet as of t=25.
Tap to reveal solution
Harddesignheap

Design: Limit Order Book With Best Bid/Offer and Lazy-Deleted Cancels

Design an OrderBook supporting add_order(order_id, side, price) where side is 'buy' or 'sell', cancel_order(order_id), best_bid() returning the highest active buy price (or None), and best_ask() returning the lowest active sell price (or None). Cancellations are frequent relative to adds, so cancel must not require scanning the book.

Input:
add_order(1,'buy',100); add_order(2,'buy',101); add_order(3,'sell',105); best_bid(); best_ask(); cancel_order(2); best_bid()
Output:
101, 105, 100
After the three adds, best_bid is 101 (the higher of the two buys) and best_ask is 105. Cancelling order 2 (the 101 buy) drops the best bid back down to 100, the only remaining active buy.
Tap to reveal solution
Mediumprobabilitymarkov-chainmath

Expected Number of Ticks Until a Position Hits Either Barrier

A position's mark-to-market P&L moves in discrete unit ticks: up one tick with probability p, down one tick with probability 1-p, independently each tick. Starting at P&L 0, the position is closed the instant P&L first hits either +a (take-profit) or -b (stop-loss). Compute, in closed form -- no simulation -- the EXPECTED NUMBER OF TICKS until the position closes.

Input:
a=3, b=2, p=0.5
Output:
6.0
For a fair walk the symmetric gambler's-ruin expected-duration formula reduces to i*(N-i) with N=a+b=5 and i=b=2, giving 2*3=6.0.
Input:
a=3, b=2, p=0.7
Output:
5.35
With upward drift the walk tends to reach a barrier faster than the fair-coin case; the general asymmetric closed form gives about 5.35 expected ticks.
Tap to reveal solution
Mediumdynamic-programming#714

Max Profit With Unlimited Round Trips, Each Charged a Flat Transaction Fee

Given a daily price array and an integer fee, you may complete as many buy-then-sell round trips as you like (must fully sell before buying again), but each completed round trip costs fee, charged once per round trip. Return the maximum achievable profit net of fees.

Input:
prices = [1,3,2,8,4,9], fee = 2
Output:
8
Buy at 1, sell at 8, netting 8-1-2=5. Then buy at 4, sell at 9, netting 9-4-2=3. Total 5+3=8, which beats any other combination of round trips once the fee is paid on each one.
Tap to reveal solution
Hardprobabilitymarkov-chainlinear-algebra

Steady-State Probabilities of a Market Regime Chain

A simple regime model classifies each trading day as Trending, Mean-Reverting, or Choppy, with a given day-to-day transition probability matrix P (rows sum to 1). Compute the long-run (stationary) fraction of days spent in each regime -- the distribution pi such that pi = pi @ P -- without simulating thousands of days.

Input:
P = [[0.7,0.2,0.1],[0.3,0.5,0.2],[0.2,0.3,0.5]]
Output:
pi ~ [0.500, 0.300, 0.200]
Solved directly as a linear system, not by iterating the chain forward.
Tap to reveal solution
Hardmerge-sortdivide-and-conquer

Counting Rank Disruption Between Two Daily Signal Rankings

You rank your universe of stocks by a signal each day. Given yesterday's ranking (a list of ticker indices, best to worst) and today's ranking of the SAME tickers, count the number of ticker pairs whose relative order flipped between the two days -- a proxy for how much the ranking churned. Do this faster than the O(n^2) all-pairs comparison.

Input:
yesterday=[0,1,2,3], today=[2,0,3,1]
Output:
3
Re-express today's ranking as the sequence of yesterday's rank-positions in today's order: ticker 2 was rank 2, ticker 0 was rank 0, ticker 3 was rank 3, ticker 1 was rank 1, giving [2,0,3,1]. Counting inversions in that sequence -- (2,0), (2,1), (3,1) -- gives 3, matching the pairs whose relative order flipped.
Tap to reveal solution
Mediumdesign

Design a FIFO Position Tracker With Average Cost Basis and Realized P&L on Partial Closes

Design a class PositionTracker supporting buy(ticker, price, qty) and sell(ticker, price, qty), maintaining each ticker's open lots in FIFO order (oldest shares are closed first), and get_position(ticker) returning the current net quantity held and the average cost basis of the REMAINING open lots. sell() should also return the realized P&L generated by that specific sell call, computed against the FIFO-matched lots it closes.

Input:
buy("AAPL", 100.0, 10); buy("AAPL", 110.0, 10); sell("AAPL", 130.0, 15); get_position("AAPL")
Output:
realized P&L from sell: 400.0; remaining position: (qty=5, avg_cost=110.0)
The sell of 15 shares closes the first lot entirely (10 shares bought at 100, profit (130-100)*10 = 300) then closes 5 shares from the second lot (bought at 110, profit (130-110)*5 = 100), for total realized P&L 400.0. The remaining open position is 5 shares still carrying the second lot's 110.0 cost basis, since FIFO always exhausts the oldest lot before touching a newer one.
Tap to reveal solution
Easyarrayhash-map#1

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Input:
nums = [2,7,11,15], target = 9
Output:
[0,1]
nums[0] + nums[1] == 9
Input:
nums = [3,2,4], target = 6
Output:
[1,2]
Tap to reveal solution
Harddynamic-programming

Maximum Profit With At Most K Buy/Sell Transactions

Given daily prices for a stock and an integer k, return the maximum profit achievable using at most k non-overlapping transactions (never holding more than one share at a time).

Input:
prices=[3,2,6,5,0,3], k=2
Output:
7
Buy at 2, sell at 6 (profit 4), then buy at 0, sell at 3 (profit 3), for a total of 7 across exactly 2 transactions -- no choice of at most 2 transactions beats this.
Tap to reveal solution
Harddesignheaphash-map

Design an Aggregated Price-Level Order Book Snapshot

Design a single-side (say, bids) order book that supports add(order_id, price, quantity), cancel(order_id), and top_levels(n), where top_levels returns the n best price levels as (price, total_quantity) pairs, aggregated across every resting order at that price, sorted best price first. All three operations should be efficient even with many orders resting across relatively few distinct price levels.

Input:
add(1,100,50); add(2,100,30); add(3,99,20); top_levels(2)
Output:
[(100, 80), (99, 20)]
Orders 1 and 2 both rest at price 100 and aggregate to a total quantity of 80 at that level; order 3 rests alone at price 99 with quantity 20. Sorted best-bid-first (highest price first), the top 2 levels are (100, 80) then (99, 20).
Tap to reveal solution
Mediumprobabilitymath

Expected Number of Ticks Until a Market Maker's Inventory Hits Flat or the Risk Limit

Same setup as the classic gambler's-ruin inventory walk: inventory starts at i shares, 0 < i < N, each tick moves +1 (probability p) or -1 (probability 1-p), and trading halts the instant inventory hits 0 or N. Compute the expected number of ticks until trading halts, given N, i, and p.

Input:
N=10, i=4, p=0.5
Output:
24.0
For a fair (p=0.5) walk, expected ticks to absorption reduces to the closed form i*(N-i) = 4*6 = 24.
Tap to reveal solution
Mediumsliding-windowtwo-pointer

Minimum Trading Days to Recoup Every Drawdown

Given a daily price series, define a drawdown episode as starting at each new running-maximum (peak) and ending on the first later day where price recovers to at least that peak level. Return the length, in trading days, of the LONGEST such episode. A final peak that is never recovered by the last day does not count.

Input:
prices=[100,90,80,85,95,105,70,72,110]
Output:
5
The peak of 100 set on day 0 isn't recovered until day 5 (price 105) -- a 5-day episode. That day 5 peak of 105 is then recovered on day 8 (price 110) -- only a 3-day episode. The longest is 5.
Tap to reveal solution
#1 of 538