Sum Active Loan Balances Per Borrower
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
A consumer-credit system tracks individual loan contracts in a loans table with the schema below:
| Column | Type | Description |
|---|---|---|
loan_id |
INTEGER |
Unique identifier of the loan contract |
borrower_id |
INTEGER |
Identifier of the customer holding the contract |
amount |
DECIMAL(12,2) |
Principal balance of the loan |
status |
VARCHAR |
Lifecycle state (for example, 'ACTIVE', 'CLOSED', 'DEFAULTED', or 'PAID_OFF') |
payment_date |
DATE |
Scheduled or latest payment date ('YYYY-MM-DD') |
Determine the combined principal across active contracts per customer:
- Include only rows whose
statusis'ACTIVE'(exact case-sensitive match). - Group those active rows by
borrower_idand sumamountwithin each customer's group. - Exclude any customer who holds zero
'ACTIVE'loans (do not output a0entry for inactive-only customers). - Order the resulting rows by
borrower_idin ascending numeric order.
In SQL, produce two columns (borrower_id, total_active_amount). In Python, implement active_loan_totals(loans), where loans is a list of row dictionaries containing "loan_id", "borrower_id", "amount", "status", and "payment_date", and return a list of two-element lists [borrower_id, total_active_amount] sorted by borrower_id ascending.
Examples
Example 1
Input (loans):
loans = [
{"loan_id": 201, "borrower_id": 310, "amount": 4200, "status": "ACTIVE", "payment_date": "2025-02-01"},
{"loan_id": 202, "borrower_id": 105, "amount": 9000, "status": "CLOSED", "payment_date": "2024-08-19"},
{"loan_id": 203, "borrower_id": 208, "amount": 1500, "status": "ACTIVE", "payment_date": "2025-01-12"},
{"loan_id": 204, "borrower_id": 310, "amount": 2800, "status": "ACTIVE", "payment_date": "2025-03-10"},
{"loan_id": 205, "borrower_id": 208, "amount": 6000, "status": "DEFAULTED", "payment_date": "2024-11-04"},
{"loan_id": 206, "borrower_id": 412, "amount": 3300, "status": "PAID_OFF", "payment_date": "2024-09-30"},
]
Output: [[208, 1500], [310, 7000]]
Explanation: Customer 208 has one 'ACTIVE' loan (1500) and one 'DEFAULTED' loan (6000, ignored), giving 1500. Customer 310 has two 'ACTIVE' loans (4200 + 2800 = 7000). Customers 105 and 412 have no 'ACTIVE' loans and are omitted. Sorting borrower_id ascending places 208 before 310.
Example 2
Input (loans):
loans = [
{"loan_id": 301, "borrower_id": 88, "amount": 2500, "status": "CLOSED", "payment_date": "2024-05-01"},
{"loan_id": 302, "borrower_id": 92, "amount": 5100, "status": "DEFAULTED", "payment_date": "2024-06-15"},
]
Output: []
Explanation: Neither contract is 'ACTIVE', so the output is empty.
Constraints
0 <= len(loans) <= 10^5loan_idvalues are distinct positive integers.1 <= borrower_id <= 10^90 < amount <= 10^9(intorfloat; integer sums remainintwhen every summedamountis anint).statusis a non-empty string.
Step-by-step walkthrough
Understand the table and desired output
Each row of
loansrepresents a single loan contract with five columns:loan_id,borrower_id,amount,status, andpayment_date.We need one output row
[borrower_id, total_active_amount]for every borrower who holds at least one contract withstatus = 'ACTIVE':- Ignore inactive loans (
'DEFAULTED','CLOSED','PAID_OFF', etc.) completely. - Omit any borrower who has zero active loans (do not output them with
0). - Sort the output rows by
borrower_idascending.
In a SQL interview you write the SQL query, while the Python judge passes
loansas a list of row dictionaries toactive_loan_totals(loans). Let's build the SQL query first and then translate each clause directly into Python.- Ignore inactive loans (
Build the SQL query in execution order
Even though
SELECTis written first in SQL, a database logically processes a query in this pipeline order:1. FROM loans -> read all loan rows 2. WHERE status = 'ACTIVE' -> keep ONLY active loan rows (drop CLOSED / DEFAULTED early) 3. GROUP BY borrower_id -> bucket surviving active rows by borrower_id 4. SELECT borrower_id, -> sum `amount` inside each borrower's bucket SUM(amount) 5. ORDER BY borrower_id ASC -> sort final summary rows by borrower_id ascendingWriting those five clauses down gives the complete SQL solution:
-- Return one row per borrower with at least one ACTIVE loan, sorted by borrower_id. SELECT borrower_id, SUM(amount) AS total_active_amount FROM loans -- Filter rows BEFORE grouping so inactive loans never enter SUM() and -- borrowers with zero active loans never form a group. WHERE status = 'ACTIVE' GROUP BY borrower_id -- SQL group order is unspecified without an explicit ORDER BY. ORDER BY borrower_id ASC;Why `WHERE` beats `CASE` and `HAVING` here
Two look-alike SQL patterns produce wrong results on this problem:
SUM(CASE WHEN status = 'ACTIVE' THEN amount ELSE 0 END)withoutWHERE: because no rows are filtered out beforeGROUP BY, every borrower inloansforms a group. Borrowers105and412in Example 1 would appear in the output withtotal_active_amount = 0instead of being excluded.GROUP BY borrower_id HAVING status = 'ACTIVE':WHEREfilters individual rows before grouping, whereasHAVINGfilters whole groups after grouping. A single borrower (like208) can own both'ACTIVE'and'DEFAULTED'loans, sostatushas no single value per group! PostgreSQL and standard SQL reject this query outright; SQLite silently inspects one arbitrary row of the group and sums all of that borrower's loans (including defaulted ones).
Rule of thumb: filter individual rows in
WHERE; filter group aggregates (likeSUM(amount) > 10000) inHAVING.Translate `WHERE`, `GROUP BY`, and `SUM` into Python
Each of the first four SQL steps maps directly to a single loop over
loansand a dictionarytotal_by_borrower:WHERE status = 'ACTIVE':if loan["status"] != "ACTIVE": continue. Because we skip non-active rows first, borrowers with no active loans never entertotal_by_borrower.GROUP BY borrower_id+SUM(amount): accumulateloan["amount"]undertotal_by_borrower[borrower_id].- Why start each new key at integer
0instead of0.0? Adding integer amounts (4200 + 2800) to0keeps the result anint(7000), while adding any float (1250.50) automatically promotes the sum tofloat.
def _sum_active_by_borrower(loans: List[Dict[str, object]]) -> Dict[object, object]: total_by_borrower = {} for loan in loans: if loan["status"] != "ACTIVE": continue borrower_id = loan["borrower_id"] if borrower_id not in total_by_borrower: total_by_borrower[borrower_id] = 0 total_by_borrower[borrower_id] += loan["amount"] return total_by_borrowerTranslate `ORDER BY borrower_id ASC` into Python
Python dictionaries remember the order keys were first inserted — which reflects whichever borrower happened to appear earliest in
loans(310before208in Example 1), not ascendingborrower_id. Callingsorted(total_by_borrower)sorts the unique borrower IDs numerically in ascending order so we can build[borrower_id, total]rows:def _format_sorted_rows(total_by_borrower: Dict[object, object]) -> List[List[object]]: result = [] for borrower_id in sorted(total_by_borrower): result.append([borrower_id, total_by_borrower[borrower_id]]) return resultTrace Example 1 row by row
loan_id borrower_id amount status Passes WHERE? total_by_borrower after row ------- ----------- ------ ----------- ------------- --------------------------- 201 310 4200 'ACTIVE' Yes {310: 4200} 202 105 9000 'CLOSED' No (skip) {310: 4200} 203 208 1500 'ACTIVE' Yes {310: 4200, 208: 1500} 204 310 2800 'ACTIVE' Yes {310: 7000, 208: 1500} 205 208 6000 'DEFAULTED' No (skip) {310: 7000, 208: 1500} 206 412 3300 'PAID_OFF' No (skip) {310: 7000, 208: 1500}Sorting the keys
[310, 208]ascending produces[208, 310], giving[[208, 1500], [310, 7000]]. Borrowers105and412never had an active loan, so they never received dictionary keys and do not appear in the output.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def active_loan_totals(loans: List[Dict[str, object]]) -> List[List[object]]: # total_by_borrower: maps borrower_id -> sum of ACTIVE loan amounts, # e.g. {310: 7000, 208: 1500}. Borrowers with zero active loans never get a key. total_by_borrower = {} # Phase 1 (SQL: WHERE status = 'ACTIVE' + GROUP BY borrower_id + SUM(amount)): # Skip inactive rows BEFORE touching the dict so borrowers without active loans are omitted. for loan in loans: if loan["status"] != "ACTIVE": continue borrower_id = loan["borrower_id"] # Initialize with integer 0 so integer loan totals stay int (7000, not 7000.0), # while decimal/float loan amounts promote to float automatically. if borrower_id not in total_by_borrower: total_by_borrower[borrower_id] = 0 total_by_borrower[borrower_id] += loan["amount"] # Phase 2 (SQL: ORDER BY borrower_id ASC): # Dict keys stay in first-appearance order, so sort borrower IDs ascending before building rows. result = [] for borrower_id in sorted(total_by_borrower): result.append([borrower_id, total_by_borrower[borrower_id]]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Picture sorting a stack of paper loan folders on an analyst's desk to find how much active debt each customer currently holds. First, you set aside every 'CLOSED', 'DEFAULTED', or 'PAID_OFF' folder before doing any math (WHERE status = 'ACTIVE'). Next, you sort the remaining active folders into one pile per customer (GROUP BY borrower_id), add up the dollar amounts inside each pile (SUM(amount) — an aggregation, meaning an operation that collapses multiple rows in a group into one summary number), and arrange the finished customer totals from smallest ID to largest (ORDER BY borrower_id ASC). In Python, a dictionary total_by_borrower plays the exact role of those customer piles, and sorted(total_by_borrower) performs the final ORDER BY.
Why do seemingly similar approaches go wrong? If you group every loan first and compute SUM(CASE WHEN status = 'ACTIVE' THEN amount ELSE 0 END), customers who only have closed or defaulted loans still get a pile and show up in the result with 0 instead of being omitted. Trying to filter with HAVING status = 'ACTIVE' is even worse: HAVING checks whole customer groups after rows have already been combined, so standard SQL rejects the query and SQLite silently sums inactive loans along with active ones whenever a mixed-status group passes.
Walk through Example 1's six rows:
- Loan 201 (borrower 310, 4200, 'ACTIVE'): active -> total_by_borrower = {310: 4200}.
- Loan 202 (borrower 105, 9000, 'CLOSED'): not active -> skipped (105 gets no entry).
- Loan 203 (borrower 208, 1500, 'ACTIVE'): active -> total_by_borrower = {310: 4200, 208: 1500}.
- Loan 204 (borrower 310, 2800, 'ACTIVE'): active -> 310's total becomes 4200 + 2800 = 7000.
- Loan 205 (borrower 208, 6000, 'DEFAULTED'): not active -> skipped (208 stays at 1500).
- Loan 206 (borrower 412, 3300, 'PAID_OFF'): not active -> skipped.
- Sorting keys [310, 208] ascending returns [[208, 1500], [310, 7000]].
Complexity
- Time:
O(n + b log b), wherenis the total number of loan rows andb(b <= n) is the number of distinct borrowers who have at least one active loan. We scan allnloans once doingO(1)average dictionary lookups and updates per active row, and then sort thebdistinct borrower IDs inO(b log b)time. - Space:
O(b), becausetotal_by_borrowerandresulteach store one entry per borrower with at least one active loan.
In a SQL database without indexes, the engine scans all n rows of loans, hashes or sorts the active rows by borrower_id, and sorts the b groups. Creating a covering index on (status, borrower_id, amount) — an index structure that stores every column the query needs in sorted tree order so the database never has to read the underlying table pages — lets the engine jump straight to status = 'ACTIVE', stream rows already ordered by borrower_id, and sum amount in one sequential pass with no extra sort step. Databases like PostgreSQL also support a partial index (CREATE INDEX ... ON loans (borrower_id, amount) WHERE status = 'ACTIVE'), which indexes only active rows to save disk and memory when historical closed loans dominate the table.
Edge cases
- Empty
loanstable or zero'ACTIVE'rows:total_by_borrowerstays empty andactive_loan_totalsreturns[]. - Borrowers with only inactive loans: skipped before dictionary insertion, so they do not appear with
0. - Borrowers with a mix of active and inactive loans: only
'ACTIVE'rows pass the guard check;'CLOSED'and'DEFAULTED'amounts for that same borrower are ignored. - Duplicate active loan amounts (
[3000, 3000, 3000]): every active loan row adds to the sum (9000), matching SQLSUM(amount)rather thanSUM(DISTINCT amount). - Cents and floating-point arithmetic: SQL
DECIMAL(12, 2)adds base-10 cents exactly, whereas binaryfloatin Python can produce tiny rounding tails like0.10 + 0.20 == 0.30000000000000004(handled by tolerance in tests; real financial pipelines usedecimal.Decimalor integer cents). - Case sensitivity on
status: Python==, SQLite=, and PostgreSQL=match'ACTIVE'case-sensitively, whereas MySQL default case-insensitive collations also match'active'. Normalize explicitly withUPPER(status) = 'ACTIVE'if upstream data has inconsistent casing. - Missing (
NULL) fields: in SQL,WHERE status = 'ACTIVE'automatically dropsNULLstatuses andSUM(amount)ignoresNULLamounts (returningNULLif every active loan for a borrower has aNULLamount). Our Python implementation assumes valid non-nullborrower_idand numericamountvalues on active loans.
Common mistakes
- Using conditional aggregation (
SUM(CASE WHEN ... ELSE 0 END)) withoutWHERE: includes borrowers who have zero active loans as[borrower_id, 0], violating the requirement to return only borrowers with at least one active loan. - Putting
status = 'ACTIVE'inHAVINGinstead ofWHERE:HAVINGevaluates per-group conditions after aggregation, not row-level filters before aggregation. - Omitting
ORDER BY borrower_id ASC(or skippingsorted(...)in Python): SQL gives no ordering guarantee afterGROUP BY, and Python dictionaries iterate in first-seen order rather than ascending numeric order. - Including non-grouped columns like
loan_idorpayment_dateinSELECT: a single borrower group can have many loan IDs and payment dates, so standard SQL rejects unaggregated non-grouped columns. - Initializing totals with
0.0in Python: turns exact integer sums like7000into7000.0.
Follow-up questions
- How would you extend the query and Python function to also report each borrower's active loan count and largest single active loan? In SQL, add more aggregate functions to
SELECTover the exact same filtered groups:SELECT borrower_id, COUNT(*) AS active_loan_count, SUM(amount) AS total_active_amount, MAX(amount) AS max_active_amount FROM loans WHERE status = 'ACTIVE' GROUP BY borrower_id ORDER BY borrower_id ASC;. In Python, store[count, total, max_amt]perborrower_idand update all three in the same single pass. - Suppose an analytics dashboard must list every registered borrower and display 0 when someone has no active loans; how does the SQL query change? Start from a
borrowersdimension table and use aLEFT JOIN(a join that keeps every row from the left table even when no matching row exists on the right, filling unmatched right-side columns withNULL) together withCOALESCE(a function that returns its first non-NULLargument, turningNULLinto0):SELECT b.borrower_id, COALESCE(SUM(l.amount), 0) AS total_active_amount FROM borrowers b LEFT JOIN loans l ON b.borrower_id = l.borrower_id AND l.status = 'ACTIVE' GROUP BY b.borrower_id ORDER BY b.borrower_id ASC;. Notice thatl.status = 'ACTIVE'must live insideON— putting it inWHEREwould throw away theNULL-padded rows and turn theLEFT JOINback into anINNER JOIN! - How would you restrict the output to borrowers whose combined active balance strictly exceeds 10000? Keep
WHERE status = 'ACTIVE'to filter individual active loans first, and addHAVING SUM(amount) > 10000right afterGROUP BY borrower_id. This combines both clauses in their natural roles:WHEREfilters raw rows before grouping, andHAVINGfilters aggregated group totals afterward.
Follow-up questions
- How would you extend the query and Python function to also report each borrower's active loan count and largest single active loan?
- Suppose an analytics dashboard must list every registered borrower and display 0 when someone has no active loans; how does the SQL query change?
- How would you restrict the output to borrowers whose combined active balance strictly exceeds 10000?
Similar questions
- Pair Sum Existence Check
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression
More LendingClub interview questions
- Pair Sum Existence Check Medium