Sum Open Credit Balances per Customer, Sorted by ID
SQL & DataAuto-graded · 13 test casesLast updated
Filter records by a status value, total a numeric field per customer ID, and return the results sorted by ID, mirroring a SQL filter, group and order query in Python.
You are given a list of loan records, each represented as a dictionary. Every record has these keys:
loan_id: the identifier of the loanborrower_id: the identifier of the borrower who holds the loanamount: the loan amount (a number)status: a string such as"ACTIVE","DEFAULTED"or"CLOSED"payment_date: a date string (not needed for this task)
Write a function that reproduces the result of this SQL query in Python:
SELECT borrower_id, SUM(amount)
FROM loans
WHERE status = 'ACTIVE'
GROUP BY borrower_id
ORDER BY borrower_id ASC;
Specifically:
- Consider only records whose
statusis exactly the string"ACTIVE". The comparison is case-sensitive and exact, so"active"or"ACTIVE "does not match. - For each borrower that has at least one such record, add up the
amountvalues of that borrower's matching records. - Return a list of two-element lists
[borrower_id, total], one per borrower, sorted byborrower_idin ascending order.
A borrower with no ACTIVE loans must not appear in the output. If no record matches, or the input list is empty, return an empty list.
Constraints
0 <= len(loans) <= 10^5borrower_idvalues are integers and can be compared with each other.amountis a number (integer or float); use plain addition to total it.- Each borrower appears at most once in the output.
- The output must be sorted by
borrower_idascending.
Examples
Example 1
Input: sum_open_balances([{'loan_id': 1001, 'borrower_id': 501, 'amount': 5000, 'status': 'ACTIVE', 'payment_date': '2024-01-15'}, {'loan_id': 1002, 'borrower_id': 502, 'amount': 7000, 'status': 'DEFAULTED', 'payment_date': '2023-12-20'}, {'loan_id': 1003, 'borrower_id': 501, 'amount': 3000, 'status': 'ACTIVE', 'payment_date': '2024-02-10'}, {'loan_id': 1004, 'borrower_id': 503, 'amount': 4500, 'status': 'CLOSED', 'payment_date': '2023-11-01'}, {'loan_id': 1005, 'borrower_id': 504, 'amount': 6500, 'status': 'ACTIVE', 'payment_date': '2024-03-05'}])
Output: [[501, 8000], [504, 6500]]
Hints
Hint 1
Think of the work as three steps in order: filter the rows, group them by borrower, then sort the groups.
Hint 2
A dictionary keyed by borrower_id works as the running total. Only create an entry when you see an ACTIVE record, so borrowers without active loans never show up.
Hint 3
Build the output from the dictionary's keys in sorted order, producing [borrower_id, total] for each.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a filter, then aggregate, then sort pipeline.
- Walk through the records once. Skip any record whose
statusis not exactly"ACTIVE". - For each remaining record, add its
amountto a dictionary entry keyed byborrower_id. A missing key starts at 0. - After the pass, sort the dictionary keys and emit
[borrower_id, total]for each one.
Why it is correct
- Non-active records are discarded before any summing, so each total contains only active loans, just as
WHEREruns beforeGROUP BYin SQL. - A dictionary entry is created only when an active record is seen. Borrowers without active loans therefore never appear.
- The dictionary has one key per borrower, so each borrower is output exactly once with the sum of all their active amounts.
- Sorting the keys gives the required ascending order by
borrower_id. - An empty input, or one with no active records, leaves the dictionary empty and the function returns
[].
Complexity
Let n be the number of records and k the number of distinct borrowers with active loans.
- Time: O(n + k log k), one pass plus sorting the keys.
- Space: O(k) for the totals and the output.
Reference solution
from typing import Dict, List
def sum_open_balances(loans: List[Dict[str, object]]) -> List[List[object]]:
totals = {}
for loan in loans:
if loan["status"] == "ACTIVE":
borrower_id = loan["borrower_id"]
totals[borrower_id] = totals.get(borrower_id, 0) + loan["amount"]
return [[borrower_id, totals[borrower_id]] for borrower_id in sorted(totals)]