← Problems77. Running balance per accountMediumPySpark
00:00 / 20:00

Running balance per account

Medium100% solve itAsked at Microsoft, PayPal, TCS

A statement shows the balance after every transaction, not just the total.

Input

transactions txn_id bigint -- unique account_id string posted_at string -- ISO-8601 UTC, 'YYYY-MM-DDTHH:MM:SSZ' amount double -- negative for a withdrawal, null if unposted

Output

Every input row, with the columns txn_id, account_id, posted_at, amount and balance — the sum of this account's amount up to and including this transaction, rounded to 2 decimal places.

Order by posted_at, breaking ties with the smaller txn_id first.

Example

txn_idaccount_idposted_atamountbalance
1A12024-01-01T00:00:00Z100.0100.0
2A12024-01-02T00:00:00Z50.0150.0
3A12024-01-03T00:00:00Z-30.0120.0

Constraints

  • Two transactions can share a posted_at. They get different balances, in txn_id order — the earlier one does not yet include the later.
  • That is also where the default window frame bites. An ordered window with no frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE advances a whole group of tied rows at once.
  • A null amount adds nothing and does not blank the balance.
  • Row order is not graded. Column names and their order are.

Example 1two deposits and a withdrawal

Input · transactions
amounttxn_idposted_ataccount_id
10012024-01-01T00:00:00ZA1
5022024-01-02T00:00:00ZA1
-3032024-01-03T00:00:00ZA1
Output
txn_idaccount_idposted_atamountbalance
1A12024-01-01T00:00:00Z100100
2A12024-01-02T00:00:00Z50150
3A12024-01-03T00:00:00Z-30120

Example 2two accounts do not pool their money

Input · transactions
amounttxn_idposted_ataccount_id
1012024-02-01T00:00:00ZA1
9922024-02-01T00:00:00ZA2
532024-02-02T00:00:00ZA1
Output
txn_idaccount_idposted_atamountbalance
1A12024-02-01T00:00:00Z1010
2A22024-02-01T00:00:00Z9999
3A12024-02-02T00:00:00Z515

Topics

window functions

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.py
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.