Top Five Senders and Receivers From Signed Transfer Logs
Arrays & HashingAuto-graded · 22 test casesLast updated
Count senders and receivers from signed transfer records in a single pass, then pick the five most frequent on each side with a deterministic tie-break.
Top Five Senders and Receivers From Signed Transfer Logs
You are given a collection of transfer records. Each record is a triple (record_id, pair, amount):
record_idis an integer identifier. It plays no part in the answer.pairis a string of the form"a:b", whereaandbare integer user ids.amountis an integer that may be negative, zero, or positive.
Direction rule
- If
amount >= 0(zero included), the record is read as written: userais the sender and userbis the receiver. - If
amount < 0, the direction is reversed: userbis the sender and userais the receiver.
Only the direction matters. The size of the amount is never used.
Task
Implement a function that returns two lists:
- The ids of the 5 users who sent the most transfers.
- The ids of the 5 users who received the most transfers.
Both lists are ordered by transfer count descending. Users with equal counts are ordered by user id ascending.
Every record counts exactly once toward one sender and once toward one receiver. Records are never deduplicated, even if record_id values repeat. A self-transfer such as "3:3" counts as one send and one receive for user 3.
Only users with a count of at least 1 on a given side can appear in that side's list. If fewer than 5 such users exist, return the shorter list without padding. For empty input, return two empty lists.
The return value is a pair (top_senders, top_receivers).
Aim for O(n) time and O(u) extra space, where u is the number of distinct users. Process each record as it arrives and do not keep per-record data around.
Constraints
0 <= n <= 10^6records.- User ids are integers, parsed from the
pairstring (which has exactly one:). amountis an integer;amount == 0is treated as non-negative.- The input may be any iterable of records, so make a single pass over it.
- The output must be deterministic and follow the stated tie-break exactly.
Examples
Example 1
Input: top_senders_and_receivers([[1001, '1:2', 50], [1002, '2:1', -20], [1003, '3:1', 10], [1004, '1:3', -5], [1005, '4:5', 15]])
Output: [[1, 3, 4], [1, 2, 5]]
Example 2
Input: top_senders_and_receivers([[1, '10:20', 100], [2, '20:30', -50], [3, '10:30', 0], [4, '30:10', -10], [5, '20:10', 25]])
Output: [[10, 20, 30], [20, 30, 10]]
Hints
Hint 1
Apply the direction rule as soon as you parse a record, so that afterwards you only deal with a (sender, receiver) pair.
Hint 2
Keep two hash-map counters, one for sends and one for receives. Each record increments exactly one entry in each.
Hint 3
Rank by the key (-count, user_id). Taking the 5 smallest keys gives the required order directly, and a heap-based selection avoids sorting all users.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Resolve the direction of each record first, then count.
- Walk through the records once. For each one, split
pairon:and convert both parts to integers. - If
amount < 0, swap the two ids. Now you know the real sender and receiver. - Add 1 to the sender's entry in a
sentcounter and add 1 to the receiver's entry in areceivedcounter. - After the pass, select the 5 best users from each counter using the key
(-count, user_id). The smallest keys belong to the highest counts, and among equal counts to the lowest ids.heapq.nsmallestreturns them already sorted.
Why it is correct
- Each record contributes exactly one send and one receive, in the direction given by the sign rule, so the counters hold exact per-user totals.
- Zero amounts fall into the "as written" branch because the test is strictly
< 0. - The key
(-count, user_id)is unique per user, so the order is total and the output is deterministic. It matches "count descending, then id ascending." - Users who never sent (or never received) are absent from that counter, so they cannot appear in its list. Fewer than 5 users simply gives a shorter list, and empty input gives two empty lists.
- Nothing is deduplicated, and
record_idis ignored, as required.
Complexity
- Time: O(n) for the counting pass, plus O(u) for each
nsmallest(5, ...)call, since k = 5 is constant. Since u <= 2n, the total is O(n). - Space: O(u) for the two counters. Records are processed one at a time and discarded, so a streaming iterable works.
Reference solution
from collections import Counter
from heapq import nsmallest
from typing import List, Tuple
def top_senders_and_receivers(logs: List[Tuple[int, str, int]]) -> Tuple[List[int], List[int]]:
sent = Counter()
received = Counter()
for record_id, pair, amount in logs:
a, b = map(int, pair.split(':'))
if amount < 0:
sender, receiver = b, a
else:
sender, receiver = a, b
sent[sender] += 1
received[receiver] += 1
top_s = nsmallest(5, sent.items(), key=lambda item: (-item[1], item[0]))
top_r = nsmallest(5, received.items(), key=lambda item: (-item[1], item[0]))
return ([uid for uid, _ in top_s], [uid for uid, _ in top_r])