KatInterview

Sum Open Credit Balances per Customer, Sorted by ID

SQL & DataAuto-graded · 13 test cases
EasyAuto-gradedSQL & Datahash-mapaggregationgroup-by

Last 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 loan
  • borrower_id: the identifier of the borrower who holds the loan
  • amount: 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:

  1. Consider only records whose status is exactly the string "ACTIVE". The comparison is case-sensitive and exact, so "active" or "ACTIVE " does not match.
  2. For each borrower that has at least one such record, add up the amount values of that borrower's matching records.
  3. Return a list of two-element lists [borrower_id, total], one per borrower, sorted by borrower_id in 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^5
  • borrower_id values are integers and can be compared with each other.
  • amount is 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_id ascending.

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.