Top Monthly Customers Under Competition Ranking
Easy · Data Manipulation (SQL/Python) · Data Engineer · Technical Screen
Problem Statement
Given transaction-level customer revenue records and a positive rank cutoff top_rank, produce a monthly leaderboard of top-spending customers per calendar month.
In Python, implement:
def rank_customers_by_month(revenue_events: List[List], top_rank: int) -> List[List]:
- Each element of
revenue_eventshas the form[event_id, customer_id, revenue_date, amount], whereevent_idandcustomer_idare integers,revenue_dateis an ISO date string'YYYY-MM-DD', andamountis a non-negative number (intor decimalfloatwith up to two fractional digits). top_rankis a positive integer (top_rank >= 1) giving the highest rank number still eligible for the output.- Return a list of
[month_start, customer_id, total_revenue, revenue_rank]rows, wheremonth_startis'YYYY-MM-01'(the first day of that calendar month).
In the equivalent PostgreSQL schema, revenue_events(event_id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, revenue_date DATE NOT NULL, amount NUMERIC(14,2) NOT NULL) holds the raw events and ranking_policy(top_rank INTEGER NOT NULL) holds a single configuration row, with a read-only query returning (month_start, customer_id, total_revenue, revenue_rank).
Apply these aggregation, ranking, and ordering rules:
- Monthly summation first: Within each calendar month (
'YYYY-MM-01'), sum everyamountbelonging to the samecustomer_idbefore computing ranks. Customers with zero events during a month do not appear in that month. - Competition ranking (
RANK): Inside each calendar month independently, rank customer totals from largest to smallest. Customers whose monthly sums are equal receive the exact samerevenue_rank, and the next lower sum receives1 +the count of customers in that month with strictly higher totals (for instance,1, 1, 3). - Cutoff filtering: Include every customer-month row satisfying
revenue_rank <= top_rank. All customers tied attop_rankare kept, even when doing so returns more thantop_rankrows for that month. - Deterministic output order: Sort the returned rows by
month_startascending, thenrevenue_rankascending, thencustomer_idascending.customer_idorders tied rows for display only and never altersrevenue_rank.
Examples
Example 1
Input:
revenue_events = [
[101, 8, '2025-03-04', 150],
[102, 5, '2025-03-09', 95],
[103, 5, '2025-03-22', 55],
[104, 12, '2025-03-18', 130]
]
top_rank = 2
Output:
[['2025-03-01', 5, 150, 1], ['2025-03-01', 8, 150, 1]]
Walk-through: In March 2025, customer 5 sums to 95 + 55 = 150, matching customer 8 at 150, while customer 12 has 130. Customers 5 and 8 tie at competition rank 1 (listed with 5 before 8), which pushes customer 12 to rank 3. Because 3 > top_rank (2), customer 12 is omitted.
Example 2
Input:
revenue_events = [
[1, 30, '2025-07-02', 200],
[2, 10, '2025-07-14', 140],
[3, 20, '2025-07-28', 140],
[4, 40, '2025-07-30', 80],
[5, 40, '2025-08-03', 175],
[6, 10, '2025-08-19', 120]
]
top_rank = 2
Output:
[
['2025-07-01', 30, 200, 1],
['2025-07-01', 10, 140, 2],
['2025-07-01', 20, 140, 2],
['2025-08-01', 40, 175, 1],
['2025-08-01', 10, 120, 2]
]
Walk-through: In July 2025, customer 30 takes rank 1 (200), customers 10 and 20 both share rank 2 (140), and customer 40 lands at rank 4 (80, excluded); all three July rows with rank <= 2 are returned. August 2025 is ranked on its own: customer 40 (175, rank 1) and customer 10 (120, rank 2), while customers 20 and 30 have no August activity.
Example 3
Input:
revenue_events = [
[1, 7, '2024-12-30', 42.5],
[2, 7, '2025-01-02', 19.2],
[3, 7, '2025-01-15', 5.8],
[4, 3, '2025-01-20', 25],
[5, 9, '2025-01-25', 24.75]
]
top_rank = 1
Output:
[
['2024-12-01', 7, 42.5, 1],
['2025-01-01', 3, 25, 1],
['2025-01-01', 7, 25, 1]
]
Walk-through: December 2024 and January 2025 are separate monthly buckets across the year boundary. In January 2025, customer 7 sums exactly to 19.2 + 5.8 = 25, tying customer 3 (25) for rank 1 ahead of customer 9 (24.75, rank 3).
Constraints
revenue_eventshas0or more rows;event_idvalues are distinct integers,customer_idvalues are integers, and everyamount >= 0has at most two decimal places.top_rank >= 1is supplied dynamically as an input parameter (or viaranking_policy), never hard-coded.- Exact decimal summation must be preserved so fractional amounts that add to the same total (such as
0.10 + 0.20and0.30) tie cleanly. - If
revenue_eventsis empty, return[].
Step-by-step walkthrough
Understand the goal and ranking rules
We are given individual
revenue_events([event_id, customer_id, revenue_date, amount]) and a positive rank cutofftop_rank. For every calendar month that has events, we must:- Sum each customer's spending within that calendar month, labeled by
month_start('YYYY-MM-01'). - Rank customers within each month from highest total to lowest using competition ranking (
RANKin SQL): customers with equal monthly sums share the exact same rank, and the next lower sum jumps ahead to its 1-based position. - Keep every row with
revenue_rank <= top_rank, sorted bymonth_startascending,revenue_rankascending, andcustomer_idascending.
Seeing all three common SQL ranking styles side by side makes competition ranking unmistakable:
Customer Monthly Total Competition RANK() DENSE_RANK() ROW_NUMBER() 5 150.00 1 1 1 8 150.00 1 1 2 <- breaks tie! 12 130.00 3 (skips 2!) 2 3Notice two crucial consequences when
top_rank = 2on the table above: - Customer12has rank3 > 2, so only2rows come back (5and8), and nobody holds rank2. - Conversely, when monthly sums are200, 140, 140withtop_rank = 2, the ranks are1, 2, 2and all three customers come back!- Sum each customer's spending within that calendar month, labeled by
Why naive event ranking or pairwise counting falls short
Two pitfalls catch people right away:
- Ranking before summing: If Customer
5makes two purchases (95and55, summing to150) and Customer12makes one130purchase, ranking individual events puts130ahead of both95and55. You must collapse events to one sum per(month_start, customer_id)before computing any rank. - Counting larger totals with nested loops: Competition rank equals
1 + (number of customers in the same month with a strictly larger total). Checking every pair of customers in a month takesO(K^2)comparisons forKcustomer-month totals, whereas sorting each month's totals once computes every rank in a single linear sweep (O(K log K)).
- Ranking before summing: If Customer
Build the PostgreSQL query step by step
In PostgreSQL, we structure those exact stages with two CTEs (Common Table Expressions) — named temporary result tables introduced with
WITH:monthly_totalstruncatesrevenue_dateto the first day of its calendar month (DATE_TRUNC('month', revenue_date)keeps both year and month, andCAST(... AS DATE)converts the timestamp back to aDATE) and sumsamountper(month_start, customer_id).ranked_customersappliesRANK(), a window function that computes competition ranks inside eachPARTITION BY month_startgroup ordered bytotal_revenue DESC. Notice thatcustomer_idis not inside the window'sORDER BY— putting it there would break ties!- The outer
SELECTattaches the single-rowranking_policytable viaCROSS JOIN, filtersr.revenue_rank <= p.top_rank(since SQL does not allow filtering on a window function in the sameWHEREclause where it is computed), and sorts the final display order.
WITH monthly_totals AS ( -- Phase 1: Collapse individual events into one exact NUMERIC sum per (month, customer) SELECT CAST(DATE_TRUNC('month', revenue_date) AS DATE) AS month_start, customer_id, SUM(amount) AS total_revenue FROM revenue_events GROUP BY CAST(DATE_TRUNC('month', revenue_date) AS DATE), customer_id ), ranked_customers AS ( -- Phase 2: Assign competition ranks (1, 1, 3) within each month by total_revenue DESC. -- Keep customer_id OUT of the window ORDER BY so equal totals share the same rank. SELECT month_start, customer_id, total_revenue, RANK() OVER ( PARTITION BY month_start ORDER BY total_revenue DESC ) AS revenue_rank FROM monthly_totals ) -- Phase 3: Filter to ranks within top_rank and break display ties by customer_id ASC SELECT r.month_start, r.customer_id, r.total_revenue, r.revenue_rank FROM ranked_customers AS r CROSS JOIN ranking_policy AS p WHERE r.revenue_rank <= p.top_rank ORDER BY r.month_start ASC, r.revenue_rank ASC, r.customer_id ASC;Step 1 in Python: sum monthly totals with exact decimals
In Python, summing binary
floatnumbers directly introduces rounding noise:0.1 + 0.2evaluates to0.30000000000000004, which does not equal0.3! That tiny error would split two tied customers into different ranks.Instead, we convert each
amountwithDecimal(str(amount))from Python's built-indecimalmodule, which performs exact base-10 arithmetic just like SQL'sNUMERIC(14, 2). And becauserevenue_dateis an ISO string'YYYY-MM-DD', slicing the first seven characters and appending'-01'(revenue_date[:7] + "-01") turns'2025-03-22'directly into'2025-03-01'.from decimal import Decimal from typing import Dict, List def _aggregate_monthly_totals(revenue_events: List[List]) -> Dict[str, Dict[int, Decimal]]: # monthly_totals: dict mapping 'YYYY-MM-01' -> {customer_id: exact Decimal sum} # e.g. {'2025-03-01': {5: Decimal('150'), 8: Decimal('150'), 12: Decimal('130')}} monthly_totals: Dict[str, Dict[int, Decimal]] = {} # Phase 1: Sum every event per (month_start, customer_id) BEFORE ranking. # Decimal(str(amount)) avoids binary float drift (0.1 + 0.2 != 0.3), keeping ties exact. for event_id, customer_id, revenue_date, amount in revenue_events: month_start = revenue_date[:7] + "-01" if month_start not in monthly_totals: monthly_totals[month_start] = {} customer_totals = monthly_totals[month_start] exact_amount = Decimal(str(amount)) customer_totals[customer_id] = customer_totals.get(customer_id, Decimal(0)) + exact_amount return monthly_totalsStep 2 in Python: sort each month and assign competition ranks
For each
month_start(sorted chronologically), we sort that month's(customer_id, total_revenue)pairs using the key(-total_revenue, customer_id). Negatingtotal_revenueputs the largest totals first, andcustomer_idorders tied customers from smallest ID to largest — matching the required final output order.Now watch how a 1-based
positioncounter (enumerate(..., start=1)) produces competition ranks in one pass:Sorted (customer_id, total) 1-based position Different from previous? current_rank (30, 200) 1 Yes (200 != None) 1 (10, 140) 2 Yes (140 != 200) 2 (20, 140) 3 No (140 == 140) 2 (kept!) (40, 80) 4 Yes ( 80 != 140) 4 (jumps to position 4!)Because
current_rankonly ever increases as totals decrease, the momentcurrent_rank > top_rankwe canbreakout of the month's loop immediately — after having already included every customer tied attop_rank.from decimal import Decimal from typing import Any, List, Optional, Tuple def _customer_sort_key(item: Tuple[int, Decimal]) -> Tuple[Decimal, int]: customer_id, total_revenue = item # Highest revenue first (-total_revenue); ties ordered by customer_id ascending for display. return (-total_revenue, customer_id) def rank_customers_by_month(revenue_events: List[List], top_rank: int) -> List[List]: monthly_totals = _aggregate_monthly_totals(revenue_events) result: List[List] = [] # Phase 2: Process months in chronological order ('YYYY-MM-01' strings sort chronologically). for month_start in sorted(monthly_totals.keys()): sorted_customers = sorted(monthly_totals[month_start].items(), key=_customer_sort_key) current_rank = 0 previous_total: Optional[Decimal] = None # Phase 3: Assign 1-based competition ranks (1, 1, 3) and stop once rank > top_rank. for position, (customer_id, total_revenue) in enumerate(sorted_customers, start=1): # Only update rank when revenue changes; equal totals keep the same rank, # while the next distinct total jumps to its 1-based position. if total_revenue != previous_total: current_rank = position previous_total = total_revenue if current_rank > top_rank: break # Return clean int for whole-number totals and float for fractional decimals. if total_revenue == int(total_revenue): output_revenue: Any = int(total_revenue) else: output_revenue = float(total_revenue) result.append([month_start, customer_id, output_revenue, current_rank]) return resultTrace through Example 2
Let's trace Example 2 with
top_rank = 2:Input events: [1, 30, '2025-07-02', 200], [2, 10, '2025-07-14', 140], [3, 20, '2025-07-28', 140], [4, 40, '2025-07-30', 80], [5, 40, '2025-08-03', 175], [6, 10, '2025-08-19', 120] Phase 1 — monthly_totals: '2025-07-01': {30: Decimal('200'), 10: Decimal('140'), 20: Decimal('140'), 40: Decimal('80')} '2025-08-01': {40: Decimal('175'), 10: Decimal('120')} Phase 2 & 3 — sort and rank each month (top_rank = 2): Month '2025-07-01' -> sorted: [(30, 200), (10, 140), (20, 140), (40, 80)] pos 1: cust 30, total 200 != None -> rank 1 <= 2 -> emit ['2025-07-01', 30, 200, 1] pos 2: cust 10, total 140 != 200 -> rank 2 <= 2 -> emit ['2025-07-01', 10, 140, 2] pos 3: cust 20, total 140 == 140 -> rank 2 <= 2 -> emit ['2025-07-01', 20, 140, 2] pos 4: cust 40, total 80 != 140 -> rank 4 > 2 -> break! Month '2025-08-01' -> sorted: [(40, 175), (10, 120)] pos 1: cust 40, total 175 != None -> rank 1 <= 2 -> emit ['2025-08-01', 40, 175, 1] pos 2: cust 10, total 120 != 175 -> rank 2 <= 2 -> emit ['2025-08-01', 10, 120, 2]Notice that Customers
20and30had zero events in August, so neither appears under'2025-08-01'.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from decimal import Decimal def _aggregate_monthly_totals(revenue_events: List[List]) -> Dict[str, Dict[int, Decimal]]: # monthly_totals: dict mapping 'YYYY-MM-01' -> {customer_id: exact Decimal sum} # e.g. {'2025-03-01': {5: Decimal('150'), 8: Decimal('150'), 12: Decimal('130')}} monthly_totals: Dict[str, Dict[int, Decimal]] = {} # Phase 1: Sum every event per (month_start, customer_id) BEFORE ranking. # Decimal(str(amount)) avoids binary float drift (0.1 + 0.2 != 0.3), keeping ties exact. for event_id, customer_id, revenue_date, amount in revenue_events: month_start = revenue_date[:7] + "-01" if month_start not in monthly_totals: monthly_totals[month_start] = {} customer_totals = monthly_totals[month_start] exact_amount = Decimal(str(amount)) customer_totals[customer_id] = customer_totals.get(customer_id, Decimal(0)) + exact_amount return monthly_totals def _customer_sort_key(item: Tuple[int, Decimal]) -> Tuple[Decimal, int]: customer_id, total_revenue = item # Highest revenue first (-total_revenue); ties ordered by customer_id ascending for display. return (-total_revenue, customer_id) def rank_customers_by_month(revenue_events: List[List], top_rank: int) -> List[List]: monthly_totals = _aggregate_monthly_totals(revenue_events) result: List[List] = [] # Phase 2: Process months in chronological order ('YYYY-MM-01' strings sort chronologically). for month_start in sorted(monthly_totals.keys()): sorted_customers = sorted(monthly_totals[month_start].items(), key=_customer_sort_key) current_rank = 0 previous_total: Optional[Decimal] = None # Phase 3: Assign 1-based competition ranks (1, 1, 3) and stop once rank > top_rank. for position, (customer_id, total_revenue) in enumerate(sorted_customers, start=1): # Only update rank when revenue changes; equal totals keep the same rank, # while the next distinct total jumps to its 1-based position. if total_revenue != previous_total: current_rank = position previous_total = total_revenue if current_rank > top_rank: break # Return clean int for whole-number totals and float for fractional decimals. if total_revenue == int(total_revenue): output_revenue: Any = int(total_revenue) else: output_revenue = float(total_revenue) result.append([month_start, customer_id, output_revenue, current_rank]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Think of a monthly sales leaderboard that hands out medals just like the Olympics: first you gather every receipt a customer generated during that calendar month and add them onto one monthly scorecard, and then you line up the monthly scorecards from highest to lowest. Under competition ranking (RANK() in SQL — a ranking rule where tied scores share the same rank and the next score skips ahead to its 1-based position), if two customers tie for 1st place, both receive rank 1 and the next customer receives rank 3 (skipping 2nd place because two people beat them).
Why do naive approaches get this wrong? If you apply a window function (a SQL function that computes values across ordered rows without collapsing them) directly to the raw revenue_events table before grouping, a customer with ten 20 orders (200 total) loses to a customer with a single 50 order. If you break ties inside the ranking sort key using customer_id, or use ROW_NUMBER() / LIMIT top_rank, you either assign different ranks to equal revenues or chop off customers tied at the cutoff boundary. And in Python, summing standard binary float values turns 0.1 + 0.2 into 0.30000000000000004 != 0.3, silently breaking ties unless you use fixed-point decimal arithmetic (decimal.Decimal in Python or NUMERIC in SQL, which represent base-10 decimals exactly).
Here is a concrete trace of Example 1's four March events with top_rank = 2:
Raw events:
(cust 8, Mar 04, 150), (cust 5, Mar 09, 95), (cust 5, Mar 22, 55), (cust 12, Mar 18, 130)
Step 1 — Sum per (month_start, customer_id):
('2025-03-01', cust 5) -> 150
('2025-03-01', cust 8) -> 150
('2025-03-01', cust 12) -> 130
Step 2 — Sort by (-total, customer_id) and assign competition ranks:
position 1: cust 5 (150) -> new total -> rank = 1 (<= 2, keep)
position 2: cust 8 (150) -> tied! -> rank = 1 (<= 2, keep)
position 3: cust 12 (130) -> new total -> rank = 3 (> 2, stop!)
Output: [['2025-03-01', 5, 150, 1], ['2025-03-01', 8, 150, 1]]
Complexity
Let N be the number of input rows in revenue_events and K be the number of distinct (month_start, customer_id) pairs (K <= N).
- Time: expected
O(N + K log K). Phase 1 scans allNevents once, doingO(1)expected-time dictionary lookups and exactDecimaladditions; Phase 2 sorts the month keys and sorts each month's customer totals, which across all months totals at mostO(K log K)comparisons; Phase 3 walks each sorted month once (O(K)at most, stopping early whencurrent_rank > top_rank). - Space:
O(K). The nestedmonthly_totalsdictionary, per-month sorted lists, and output list store at most one entry per distinct(month_start, customer_id)pair.
In PostgreSQL, the monthly_totals CTE (a named WITH subquery) scans the N events once to aggregate into K rows, RANK() OVER (PARTITION BY month_start ORDER BY total_revenue DESC) sorts those K aggregated rows (O(K log K)), and the final ORDER BY sorts only the kept top-ranked rows.
Edge cases
- Tie inside
top_rankskipping past the cutoff (Example 1): Totals150, 150, 130give ranks1, 1, 3. Withtop_rank = 2, rank3is excluded and only2rows are returned. - Tie right on
top_rankreturning more thantop_rankrows (Example 2): Totals200, 140, 140, 80give ranks1, 2, 2, 4. Withtop_rank = 2, all three customers with rank<= 2are returned. - Multiple events for the same customer in one month: All events in the same calendar month are summed before any ranking happens (
30 + 30 + 30 = 90beats85). - Same month or adjacent months across different years (
2024-12-30vs2025-01-02vs2025-12-05): Grouping by full'YYYY-MM-01'(orDATE_TRUNC('month', ...)in SQL) keeps December 2024 separate from January 2025 and December 2025. - Customer inactive in a month: Customers with zero events in August have no August row at all; they are never synthesized with
0revenue. - Explicit
0.00revenue event: A recorded event withamount = 0creates a valid customer-month total of0that participates in ranking. - Decimal cent sums (
19.2 + 5.8vs25, or0.10 + 0.20vs0.30): ExactDecimaladdition ensures fractional parts sum cleanly and share rank1. - Empty
revenue_events([]) ortop_ranklarger than customer count: Empty input returns[]; a largetop_rankcleanly returns every active customer in each month.
Common mistakes
- Applying
RANK()beforeGROUP BY: Ranking individual event amounts instead of monthly customer sums produces wrong totals and wrong winners. - Using
DENSE_RANK()orROW_NUMBER()instead ofRANK():DENSE_RANK()produces1, 1, 2(failing to skip positions after ties), whileROW_NUMBER()produces1, 2, 3(arbitrarily breaking equal-revenue ties). - Adding
customer_idtoRANK() OVER (... ORDER BY total_revenue DESC, customer_id ASC): Puttingcustomer_idinside the window'sORDER BYforces tied customers into distinct ranks (1and2).customer_idbelongs only in the final displayORDER BY. - Using
LIMIT top_rankinstead ofWHERE revenue_rank <= top_rank:LIMITcaps total output rows across the whole query rather than per month, and drops tied customers at the boundary. - Grouping by
EXTRACT(MONTH FROM revenue_date)without the year: That merges January 2024 and January 2025 into a single bucket. - Summing binary
floatvalues in Python:0.1 + 0.2 != 0.3in IEEE 754 floating point, which breaks tie detection; always sum withDecimal(str(amount))(or integer centsround(amount * 100)when inputs have at most two decimal places).
Follow-up questions
- What changes in SQL and Python if ties should use dense ranking instead of competition ranking? In SQL, swap
RANK()forDENSE_RANK(). In Python, replacecurrent_rank = positionwithcurrent_rank += 1insideif total_revenue != previous_total:, so each new distinct revenue level advances the rank by1(1, 1, 2) regardless of how many customers shared the previous rank. - How would you augment each output row with the customer's rank delta from the prior calendar month? Compute
revenue_rankfor all customer-months first (before applyingWHERE revenue_rank <= top_rank), then useLAG(revenue_rank) OVER (PARTITION BY customer_id ORDER BY month_start)together withLAG(month_start)to check whether that customer's previous active month was literallymonth_start - INTERVAL '1 month'. Apply the<= top_rankfilter in an outer CTE afterward so a customer who climbed from rank15last month to rank1this month still sees their15 -> 1jump. - How would you keep this leaderboard fast once the raw events table grows to billions of rows? Maintain an incremental monthly summary table
(month_start, customer_id, total_revenue)updated as new events stream in (or recomputed nightly only for the open month), and partitionrevenue_eventsbyrevenue_datemonthly. Ranking then readsKpre-aggregated customer-month rows instead of rescanning billions of raw events.
Follow-up questions
- What changes in SQL and Python if ties should use dense ranking instead of competition ranking?
- How would you augment each output row with the customer's rank delta from the prior calendar month?
- How would you keep this leaderboard fast once the raw events table grows to billions of rows?
Similar questions
- Longest Consecutive Full-Attendance Day Streak
- Assign Mapped or Fallback Unique IDs to Employees
- Probability of Two Uniform Arrivals Meeting
- Minimum Triangle Path Sum and Two-Dice Stopping Analysis
- Count Elements With Frequency One
- Locate Two Array Indices With a Target Sum
More Agoda interview questions
- Count Elements With Frequency One Easy
- Longest Consecutive Full-Attendance Day Streak Easy
- Assign Mapped or Fallback Unique IDs to Employees Easy Pro
- Probability of Two Uniform Arrivals Meeting Medium Pro
- Minimum Triangle Path Sum and Two-Dice Stopping Analysis Medium Pro
- Locate Two Array Indices With a Target Sum Medium Pro