---
title: Rolling transaction-velocity feature
url: https://gurkanozkan.ai/learn/coding/mle-rolling-transaction-velocity-feature-05/
markdown: https://gurkanozkan.ai/learn/coding/mle-rolling-transaction-velocity-feature-05.md
kind: coding
difficulty: Easy
topics:
  - Streaming
  - Sliding window
  - Fraud features
json: https://gurkanozkan.ai/api/learn/coding/mle-rolling-transaction-velocity-feature-05.json
robots: noindex
---

# Rolling transaction-velocity feature

`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

```python
def rolling_count(txns: list[tuple[str, int]], window: int) -> list[int]: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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]
True
```

## Hints

1. Per card keep a deque of recent timestamps; push each new ts.
2. Evict timestamps <= ts - window, keeping the half-open window (ts - window, ts].
3. Output the deque length after pushing.

## Reference solution

```python
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 out
```

## What 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.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
