KatInterview

Loan Count Gap Between Newest Member and Their Sponsor

SQL & DataAuto-graded · 13 test cases
EasyAuto-gradedSQL & Dataaggregationhash-mapnull-handling

Last updated

Tests table-style aggregation in Python: select the row with the highest key, count occurrences per key, and handle null or missing sponsor references with a default of zero.

A library tracks which members currently hold its book copies, and which member introduced each member.

You are given two tables as lists of rows:

  • copies: each row is [copy_id, held_by_member_id]. The second value is the member currently holding that copy, or None if nobody holds it.
  • members: each row is [member_id, sponsor_member_id]. The second value is the member who introduced this member, or None if there is no sponsor.

Find the member with the largest member_id in members. Return a list of exactly three values:

  1. that member's member_id,
  2. that member's sponsor_member_id (which may be None),
  3. the gap: the number of copies held by that member, minus the number of copies held by their sponsor.

Rules:

  • A copy with held_by_member_id equal to None counts for nobody.
  • If the sponsor is None, or the sponsor holds no copies, the sponsor's count is 0.
  • A sponsor id does not need to appear in members; their count is still taken from copies.
  • The gap may be negative or zero.
  • Each row in copies counts as one copy.

Return the result as [member_id, sponsor_member_id, gap].

Constraints

  • members contains at least one row, and member_id values are unique.
  • copies may be empty.
  • All ids are integers, except that held_by_member_id and sponsor_member_id may be None.
  • The result is always a list of length 3, in the order given above.

Examples

Example 1

Input: loan_gap_for_newest_member([[1, 10], [2, 10], [3, 20], [4, 30]], [[10, None], [20, 10], [30, 20]])

Output: [30, 20, 0]

Hints

Hint 1

Splitting the work into independent parts helps: pick the target member, count holdings per member, then look up two counts.

Hint 2

Build a dictionary of how many copies each member holds, skipping rows where the holder is None.

Hint 3

Use a default of 0 when looking up a count (a missing member or a None sponsor), so the subtraction never involves a missing value.