← All Exercises

Compute a Running Total per User

basicjavascript~20min

Background

Window functions are the cheapest way to add cumulative metrics. Reimplementing the arithmetic makes the partition and ordering clauses impossible to hand-wave.

Problem

Given transaction rows, produce per-user running totals ordered by day, matching what a SQL window function with PARTITION BY user ORDER BY day returns.

Input

JSON object: { rows: [{ id, user, day, amount }] }

Output

JSON array of { user, day, amount, runningTotal } sorted by user then day

Sample tests

Sample 1

Input: {"rows":[{"id":"t1","user":"alice","day":"2026-01-01","amount":10},{"id":"t2","user":"alice","day":"2026-01-02","amount":5},{"id":"t3","user":"bob","day":"2026-01-01","amount":7}]}
Expected: [{"user":"alice","day":"2026-01-01","amount":10,"runningTotal":10},{"user":"alice","day":"2026-01-02","amount":5,"runningTotal":15},{"user":"bob","day":"2026-01-01","amount":7,"runningTotal":7}]

Sample 2

Input: {"rows":[{"id":"t4","user":"bob","day":"2026-01-02","amount":3},{"id":"t5","user":"bob","day":"2026-01-02","amount":4}]}
Expected: [{"user":"bob","day":"2026-01-02","amount":3,"runningTotal":3},{"user":"bob","day":"2026-01-02","amount":4,"runningTotal":7}]

Your solution

Learning objective

Reproduce window-function semantics from raw rows.