Maintain top N payers
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Maintain top N payers states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= len(payments) <= 10^5
- 0 <= n <= number of distinct accounts (n may exceed it; return all)
- amount is a non-negative integer
- accountId is a non-empty string
- Ties are broken by lexicographically smaller accountId
Examples
Input: ([['a', 100], ['b', 50], ['a', 25], ['c', 75]], 2)
Expected Output: ['a:125', 'c:75']
Explanation: Totals: a=125, c=75, b=50. Top 2 are a then c.
Input: ([['x', 30], ['y', 30], ['z', 10]], 2)
Expected Output: ['x:30', 'y:30']
Explanation: x and y tie at 30; the smaller accountId 'x' is listed first, then 'y'. z (10) is excluded.
Input: ([], 3)
Expected Output: []
Explanation: No payments, so there are no accounts to rank.
Input: ([['solo', 500]], 5)
Expected Output: ['solo:500']
Explanation: Only one account exists; n=5 exceeds it so all accounts are returned.
Input: ([['a', 10], ['b', 20], ['c', 30]], 0)
Expected Output: []
Explanation: n=0 requests zero payers, so the result is empty.
Input: ([['b', 40], ['a', 40], ['c', 40]], 3)
Expected Output: ['a:40', 'b:40', 'c:40']
Explanation: Three-way tie at 40; all ordered by ascending accountId.
Hints
- Aggregate first: walk the payments once and accumulate each account's total in a hash map. The same account can appear in many debits.
- To rank, sort the map entries by total descending; for equal totals fall back to ascending accountId so the order is deterministic.
- For an online / streaming version, maintain a size-N min-heap (or an ordered map keyed by total) so each update is O(log N) instead of re-sorting everything.
- Watch the edge cases: n = 0 and empty payments both return an empty list, and n larger than the distinct-account count returns every account.