Find the First Transaction That Overdraws Each Wallet
Last updated: November 29, 2026
Quick Overview
Given wallet_txns(wallet_id, txn_id, created_at, amount_cents) with signed amounts, compute each wallet's running balance and return the first transaction that pushed it below zero.
PayPal
November 29, 20260
0
0 solved
Given wallet_txns(wallet_id, txn_id, created_at, amount_cents) with signed amounts, compute each wallet's running balance and return the first transaction that pushed it below zero.
PayPal balances can go negative after chargebacks, reversals or refunds that exceed incoming funds, and risk and collections teams track when that first happens. The interviewer tests cumulative window sums with a correct frame and tie-breaking, plus picking the first qualifying row per partition.
What the Interviewer Expects
- Use SUM() OVER with PARTITION BY wallet and ORDER BY time
- Specify ROWS frame to avoid RANGE ties lumping same-timestamp rows
- Break timestamp ties with txn_id
- Select the first negative row per wallet with ROW_NUMBER
- Explain why filtering before the window would be wrong
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you find every episode where the wallet went negative and later recovered?
- What if wallets hold multiple currencies?
- How would you compute this incrementally each day without rescanning history?
- How do pending or held funds change the definition of balance?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Amounts are signed integers in cents: deposits and incoming payments positive, payouts, refunds and reversals negative. The balance starts at zero for each wallet. Multiple transactions can share a ti...
Approach
First compute the running balance on all rows, then filter to rows where the balance is negative, then keep the earliest per wallet. The order matters: filtering negative rows before the running sum w...