Each transaction is a 'CREDIT' (adds amount) or 'DEBIT' (subtracts amount). Process each account's transactions in order of txn_date, then txn_id, keeping a running balance starting at 0. With Spark SQL, return for every account the FIRST transaction after which the balance is below 0, with that balance. Accounts that never go negative are not returned.
| txn_id | acct_id | txn_type | amount | txn_date |
|---|---|---|---|---|
| 1 | 10 | CREDIT | 1000.0 | 2024-01-01 |
| 2 | 10 | DEBIT | 400.0 | 2024-01-02 |
| 3 | 10 | DEBIT | 700.0 | 2024-01-03 |
| 4 | 10 | DEBIT | 100.0 | 2024-01-04 |
| 5 | 20 | CREDIT | 50.0 | 2024-01-01 |
| acct_id | txn_id | txn_date | balance |
|---|---|---|---|
| 10 | 3 | 2024-01-03 | -100 |
| txn_id | acct_id | txn_type | amount | txn_date |
|---|---|---|---|---|
| 6 | 30 | DEBIT | 20.0 | 2024-02-01 |
| 7 | 30 | CREDIT | 100.0 | 2024-02-02 |
| acct_id | txn_id | txn_date | balance |
|---|---|---|---|
| 30 | 6 | 2024-02-01 | -20 |
Return columns acct_id, txn_id, txn_date, balance. Row order does not matter. Use spark.sql.
Solve it in the live editor on this page — run on sample data, then submit against hidden tests.
‹ Second-Highest Salary per Department (or NULL) · Daily Active Users ›
{{ totalCount }} questions · {{ shHardPct }}% Hard. Real PySpark DataFrame and Spark SQL interview questions. Write PySpark in your browser on TechTown’s Spark engine, run sample tests, then submit against hidden tests.
Guests can solve {{ freeLimit }} problems for free. Log in or sign up (free) to unlock everything, keep your streak and appear on the leaderboard. New to a topic? Learn it first in the Spark course.
{{ p.statement }}
{{ p.constraints }}
No submissions yet. Press Submit to judge your code against all tests.
The model solution and step-by-step explanation unlock when you solve this problem or after 3 unsuccessful submissions ({{ shFailsLabel }}). Struggling? Try the hints on the Question tab first.
{{ p.solution }}
Write real PySpark: from pyspark.sql import functions as F, Window, spark.sql(...). It runs in your browser on a lightweight Spark engine, and the same code runs unchanged on Databricks or any Spark cluster. Use df.show() or print() to debug.
Create your free TechTown account to unlock every problem, track your progress, bookmark questions and keep preparing for interviews.