Track Top Merchants by Spend Over a Rolling Time Window
Last updated: November 29, 2026
Quick Overview
Build a structure that ingests card transactions (timestamp, merchant, amount) in time order and answers 'top k merchants by spend in the last W seconds' at any moment.
Ramp
November 29, 20260
0
0 solved
Build a structure that ingests card transactions (timestamp, merchant, amount) in time order and answers 'top k merchants by spend in the last W seconds' at any moment.
Ramp surfaces live spend insights, such as which vendors are driving this week's card spend, and anomaly checks watch for sudden concentration at one merchant. The interviewer looks for a deque-based sliding window with running totals, a heap-based top-k selection, and a clear statement of the window boundaries.
What the Interviewer Expects
- Uses a deque of events and evicts from the front as time advances
- Maintains per-merchant running totals and deletes merchants that drop to zero
- Selects top k with a heap in O(M log k) instead of a full sort
- Defines tie-breaking and the half-open window precisely
- Rejects out-of-order events or explains how to handle them
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Queries are far more frequent than writes. How would you make `top_k` O(k)?
- How would you tolerate events arriving up to 5 seconds late?
- How would this work across 1,000 businesses with separate windows?
- What if you only need approximate answers over billions of events?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
record(ts, merchant, amount) with non-decreasing ts. top_k(now, k) returns up to k (merchant, total) pairs for events with now - W < ts <= now, sorted by total descending, ties by merchant n...
High-Level Design
Keep all live events in a deque in arrival order and a dict of totals. Before every write or query, pop events whose timestamp is at or before now - W and subtract them from their merchant's total, ...