Rolling transaction-velocity feature
Problem
txns is a list of (card_id, ts) in non-decreasing ts order. For each transaction, output how many transactions of the same card have timestamps in the half-open window (ts − window, ts], counting itself and any earlier ones.
Signature
def rolling_count(txns: list[tuple[str, int]], window: int) -> list[int]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> rolling_count([('c',0),('c',10),('c',59),('c',60)], 60) == [1, 2, 3, 3]
True
>>> rolling_count([('c',0),('d',1),('c',2),('d',100)], 60) == [1, 1, 2, 1]
TrueHints
Per card keep a deque of recent timestamps; push each new ts.
Evict timestamps <= ts - window, keeping the half-open window (ts - window, ts].
Output the deque length after pushing.
Reference solution
from collections import defaultdict
from collections import deque
def rolling_count(txns, window):
q = defaultdict(deque)
out = []
for card, t in txns:
d = q[card]
d.append(t)
while d and d[0] <= t - window:
d.popleft()
out.append(len(d))
return outWhat a strong solution covers
- Per-card deque with amortised O(1) eviction.
- Exact window boundary semantics.
- Memory discussion (many cards), with TTL eviction.
- How this becomes a streaming feature (Flink/Kafka) and the same code path for training (no skew).
Common mistakes
- an off-by-one at the window edge
- recomputing the window by scanning all history.