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_events has the form [event_id, customer_id, revenue_date, amount], where event_id and customer_id are integers, revenue_date is an ISO date string 'YYYY-MM-DD', and amount is a non-negative number (int or decimal float with up to two fractional digits).
  • top_rank is 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, where month_start is '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:

  1. Monthly summation first: Within each calendar month ('YYYY-MM-01'), sum every amount belonging to the same customer_id before computing ranks. Customers with zero events during a month do not appear in that month.
  2. Competition ranking (RANK): Inside each calendar month independently, rank customer totals from largest to smallest. Customers whose monthly sums are equal receive the exact same revenue_rank, and the next lower sum receives 1 + the count of customers in that month with strictly higher totals (for instance, 1, 1, 3).
  3. Cutoff filtering: Include every customer-month row satisfying revenue_rank <= top_rank. All customers tied at top_rank are kept, even when doing so returns more than top_rank rows for that month.
  4. Deterministic output order: Sort the returned rows by month_start ascending, then revenue_rank ascending, then customer_id ascending. customer_id orders tied rows for display only and never alters revenue_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_events has 0 or more rows; event_id values are distinct integers, customer_id values are integers, and every amount >= 0 has at most two decimal places.
  • top_rank >= 1 is supplied dynamically as an input parameter (or via ranking_policy), never hard-coded.
  • Exact decimal summation must be preserved so fractional amounts that add to the same total (such as 0.10 + 0.20 and 0.30) tie cleanly.
  • If revenue_events is empty, return [].

Step-by-step walkthrough

  1. Understand the goal and ranking rules

    We are given individual revenue_events ([event_id, customer_id, revenue_date, amount]) and a positive rank cutoff top_rank. For every calendar month that has events, we must:

    1. Sum each customer's spending within that calendar month, labeled by month_start ('YYYY-MM-01').
    2. Rank customers within each month from highest total to lowest using competition ranking (RANK in SQL): customers with equal monthly sums share the exact same rank, and the next lower sum jumps ahead to its 1-based position.
    3. Keep every row with revenue_rank <= top_rank, sorted by month_start ascending, revenue_rank ascending, and customer_id ascending.

    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              3
    

    Notice two crucial consequences when top_rank = 2 on the table above: - Customer 12 has rank 3 > 2, so only 2 rows come back (5 and 8), and nobody holds rank 2. - Conversely, when monthly sums are 200, 140, 140 with top_rank = 2, the ranks are 1, 2, 2 and all three customers come back!

  2. Why naive event ranking or pairwise counting falls short

    Two pitfalls catch people right away:

    • Ranking before summing: If Customer 5 makes two purchases (95 and 55, summing to 150) and Customer 12 makes one 130 purchase, ranking individual events puts 130 ahead of both 95 and 55. 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 takes O(K^2) comparisons for K customer-month totals, whereas sorting each month's totals once computes every rank in a single linear sweep (O(K log K)).
  3. 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:

    1. monthly_totals truncates revenue_date to the first day of its calendar month (DATE_TRUNC('month', revenue_date) keeps both year and month, and CAST(... AS DATE) converts the timestamp back to a DATE) and sums amount per (month_start, customer_id).
    2. ranked_customers applies RANK(), a window function that computes competition ranks inside each PARTITION BY month_start group ordered by total_revenue DESC. Notice that customer_id is not inside the window's ORDER BY — putting it there would break ties!
    3. The outer SELECT attaches the single-row ranking_policy table via CROSS JOIN, filters r.revenue_rank <= p.top_rank (since SQL does not allow filtering on a window function in the same WHERE clause 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;
    
  4. Step 1 in Python: sum monthly totals with exact decimals

    In Python, summing binary float numbers directly introduces rounding noise: 0.1 + 0.2 evaluates to 0.30000000000000004, which does not equal 0.3! That tiny error would split two tied customers into different ranks.

    Instead, we convert each amount with Decimal(str(amount)) from Python's built-in decimal module, which performs exact base-10 arithmetic just like SQL's NUMERIC(14, 2). And because revenue_date is 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_totals
    
  5. Step 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). Negating total_revenue puts the largest totals first, and customer_id orders tied customers from smallest ID to largest — matching the required final output order.

    Now watch how a 1-based position counter (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_rank only ever increases as totals decrease, the moment current_rank > top_rank we can break out of the month's loop immediately — after having already included every customer tied at top_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 result
    
  6. Trace 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 20 and 30 had zero events in August, so neither appears under '2025-08-01'.

  7. 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 all N events once, doing O(1) expected-time dictionary lookups and exact Decimal additions; Phase 2 sorts the month keys and sorts each month's customer totals, which across all months totals at most O(K log K) comparisons; Phase 3 walks each sorted month once (O(K) at most, stopping early when current_rank > top_rank).
  • Space: O(K). The nested monthly_totals dictionary, 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_rank skipping past the cutoff (Example 1): Totals 150, 150, 130 give ranks 1, 1, 3. With top_rank = 2, rank 3 is excluded and only 2 rows are returned.
  • Tie right on top_rank returning more than top_rank rows (Example 2): Totals 200, 140, 140, 80 give ranks 1, 2, 2, 4. With top_rank = 2, all three customers with rank <= 2 are 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 = 90 beats 85).
  • Same month or adjacent months across different years (2024-12-30 vs 2025-01-02 vs 2025-12-05): Grouping by full 'YYYY-MM-01' (or DATE_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 0 revenue.
  • Explicit 0.00 revenue event: A recorded event with amount = 0 creates a valid customer-month total of 0 that participates in ranking.
  • Decimal cent sums (19.2 + 5.8 vs 25, or 0.10 + 0.20 vs 0.30): Exact Decimal addition ensures fractional parts sum cleanly and share rank 1.
  • Empty revenue_events ([]) or top_rank larger than customer count: Empty input returns []; a large top_rank cleanly returns every active customer in each month.

Common mistakes

  • Applying RANK() before GROUP BY: Ranking individual event amounts instead of monthly customer sums produces wrong totals and wrong winners.
  • Using DENSE_RANK() or ROW_NUMBER() instead of RANK(): DENSE_RANK() produces 1, 1, 2 (failing to skip positions after ties), while ROW_NUMBER() produces 1, 2, 3 (arbitrarily breaking equal-revenue ties).
  • Adding customer_id to RANK() OVER (... ORDER BY total_revenue DESC, customer_id ASC): Putting customer_id inside the window's ORDER BY forces tied customers into distinct ranks (1 and 2). customer_id belongs only in the final display ORDER BY.
  • Using LIMIT top_rank instead of WHERE revenue_rank <= top_rank: LIMIT caps 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 float values in Python: 0.1 + 0.2 != 0.3 in IEEE 754 floating point, which breaks tie detection; always sum with Decimal(str(amount)) (or integer cents round(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() for DENSE_RANK(). In Python, replace current_rank = position with current_rank += 1 inside if total_revenue != previous_total:, so each new distinct revenue level advances the rank by 1 (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_rank for all customer-months first (before applying WHERE revenue_rank <= top_rank), then use LAG(revenue_rank) OVER (PARTITION BY customer_id ORDER BY month_start) together with LAG(month_start) to check whether that customer's previous active month was literally month_start - INTERVAL '1 month'. Apply the <= top_rank filter in an outer CTE afterward so a customer who climbed from rank 15 last month to rank 1 this month still sees their 15 -> 1 jump.
  • 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 partition revenue_events by revenue_date monthly. Ranking then reads K pre-aggregated customer-month rows instead of rescanning billions of raw events.

Follow-up questions

Similar questions

More Agoda interview questions

All 7 Agoda questions →