Monthly Allocation of Annual Cent Totals

Medium · Coding & Algorithms · Backend Engineer · Technical Screen

Problem Statement

An accounting ledger books annual subscription contracts across the 12 calendar months of a year (indices 0 through 11). Given a non-negative integer total_cents representing the full contract value in cents, implement distribute_revenue(total_cents: int) -> List[int] to split that amount into a 12-element list of integer cent allocations obeying three rules:

  1. Exact conservation: Summing the 12 returned integers equals total_cents with zero pennies lost or created.
  2. Balanced spread: Monthly values differ by at most 1 cent — every entry is either total_cents // 12 or (total_cents // 12) + 1.
  3. Earliest-month priority: Whenever total_cents is not a multiple of 12, the r = total_cents % 12 leftover cents are placed 1 cent apiece onto the first r months (0, 1, ..., r - 1).

Examples

Example 1

Input:  total_cents = 3600
Output: [300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300]

Walk-through: 3600 divides evenly across 12 months (3600 // 12 == 300, 3600 % 12 == 0), so every month receives 300 cents.

Example 2

Input:  total_cents = 50
Output: [5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]

Walk-through: 50 // 12 == 4 gives a baseline of 4 cents per month (48 cents total), and the 50 % 12 == 2 leftover cents add +1 to indices 0 and 1, giving [5, 5, 4, ..., 4] summing to 50.

Example 3

Input:  total_cents = 7
Output: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

Walk-through: 7 // 12 == 0 and 7 % 12 == 7, so months 0 through 6 receive 1 cent each while months 7 through 11 receive 0.

Constraints

  • 0 <= total_cents <= 10^18
  • Return a list of length 12 containing exact int values (avoid floating-point rounding).

Step-by-step walkthrough

  1. Restate the problem and check the rules

    Given a non-negative integer total_cents representing a full year's contract revenue in cents, we must return a list of 12 integers (months 0 through 11) satisfying three accounting invariants:

    1. Exact conservation: All 12 monthly amounts add up to total_cents with zero pennies lost or gained.
    2. Balanced spread: Every month receives either total_cents // 12 or (total_cents // 12) + 1.
    3. Front-loaded leftover: Any leftover cents after dividing by 12 go 1 cent apiece to the earliest months (0, 1, ..., remainder - 1).
  2. Why floating-point division fails for money

    Dividing with / (total_cents / 12) and calling round() fails for two separate reasons:

    1. Sums drift away from the total: 50 / 12 is 4.1666..., which rounds down to 4 for every single month — summing to 48 instead of 50 and losing two cents!
    2. Large integers lose precision: Standard 64-bit floats (float) only represent every integer without gaps up to 2^53 (around 9 * 10^15). Above that threshold, float(10**18 + 7) silently rounds to 10**18 before the division even begins.

    Financial ledgers avoid floats entirely by storing money as integer cents and splitting amounts via integer quotients and remainders.

  3. Key idea: baseline quotient plus leftover remainder

    Every non-negative integer total_cents decomposes uniquely as:

    total_cents  =  12 * base_cents  +  remainder_cents     (where 0 <= remainder_cents < 12)
    

    Python gives us both pieces directly via integer floor division (base_cents = total_cents // 12) and the modulo operator (remainder_cents = total_cents % 12):

    1. First, assign base_cents to every one of the 12 months, accounting for 12 * base_cents cents.
    2. Next, remainder_cents individual pennies (0 through 11) remain. Because remainder_cents < 12, no month ever receives two extra pennies — we simply add +1 to each of the first remainder_cents months (month_index = 0, 1, ..., remainder_cents - 1):
    Example: total_cents = 50  -->  base_cents = 50 // 12 = 4,  remainder_cents = 50 % 12 = 2
    
    Month index:     0   1 |  2   3   4   5   6   7   8   9  10  11
    Extra (+1):     +1  +1 |  0   0   0   0   0   0   0   0   0   0   <-- month_index < 2
    Base (4):        4   4 |  4   4   4   4   4   4   4   4   4   4
                    -------+---------------------------------------
    Monthly total:   5   5 |  4   4   4   4   4   4   4   4   4   4   (sum = 10 + 40 = 50)
    

    Notice why strict < (month_index < remainder_cents) is exact: indices 0 through remainder_cents - 1 cover precisely remainder_cents months (and when remainder_cents == 0, month_index < 0 is False for every index).

  4. Code the 12-month loop

    We step month_index across 0 .. 11, appending base_cents + 1 whenever month_index < remainder_cents and base_cents otherwise.

    def distribute_revenue(total_cents: int) -> List[int]:
        # Phase 1: Split total_cents into an exact baseline per month plus leftover cents (0..11)
        # using integer arithmetic so floating-point rounding never loses or invents cents.
        base_cents = total_cents // 12
        remainder_cents = total_cents % 12
    
        # months: list of 12 integer cent amounts for month indices 0 (Jan) through 11 (Dec)
        months: List[int] = []
    
        # Phase 2: Give every month base_cents, plus 1 extra cent to the first remainder_cents months.
        for month_index in range(12):
            # Strict '<' gives +1 to indices 0 .. remainder_cents - 1 (exactly remainder_cents months).
            if month_index < remainder_cents:
                months.append(base_cents + 1)
            else:
                months.append(base_cents)
    
        return months
    
  5. Trace the examples and boundary cases

    Let's verify our formula across all three examples from statement.md plus 35 and 0:

    total_cents   base (// 12)   rem (% 12)   months (12 items)                         sum
    -----------   ------------   ----------   ----------------------------------------  ----
           3600            300            0   [300, 300, 300, ..., 300]                 3600
             50              4            2   [5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]        50
              7              0            7   [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]         7
             35              2           11   [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2]        35
              0              0            0   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]         0
    

    Every case produces 12 integers, keeps max-minus-min at most 1, front-loads extra pennies from index 0, and sums back to total_cents.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def distribute_revenue(total_cents: int) -> List[int]:
        # Phase 1: Split total_cents into an exact baseline per month plus leftover cents (0..11)
        # using integer arithmetic so floating-point rounding never loses or invents cents.
        base_cents = total_cents // 12
        remainder_cents = total_cents % 12
    
        # months: list of 12 integer cent amounts for month indices 0 (Jan) through 11 (Dec)
        months: List[int] = []
    
        # Phase 2: Give every month base_cents, plus 1 extra cent to the first remainder_cents months.
        for month_index in range(12):
            # Strict '<' gives +1 to indices 0 .. remainder_cents - 1 (exactly remainder_cents months).
            if month_index < remainder_cents:
                months.append(base_cents + 1)
            else:
                months.append(base_cents)
    
        return months
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture dealing a pile of pennies evenly across 12 monthly envelopes lined up from January (index 0) to December (index 11). Rather than dropping one penny at a time until the pile is gone, a single division by 12 settles the entire year: integer floor division (//, which divides and rounds down to a whole number) reveals how many complete rounds of pennies every envelope receives, while the modulo operator (%, which returns the integer remainder after division) reveals how many loose pennies (0 through 11) are left for one final partial pass starting at index 0.

Why do obvious alternatives break down? Dealing pennies one by one in a for loop takes billions of iterations on multi-million-dollar contracts, whereas floating-point division (total_cents / 12) both drifts away from total_cents after rounding and corrupts large integers because IEEE 754 64-bit floats (the binary floating-point format behind Python's float) only represent every integer without gaps up to 2^53.

Let's walk through Examples 2 and 3 — total_cents = 50 and total_cents = 7:

total_cents = 50:
  base_cents = 50 // 12 = 4,  remainder_cents = 50 % 12 = 2
  month_index < 2 is True at indices 0, 1  -->  [5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] (sum = 50)

total_cents = 7:
  base_cents = 7 // 12 = 0,   remainder_cents = 7 % 12 = 7
  month_index < 7 is True at indices 0..6  -->  [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] (sum = 7)

Complexity

  • Time: O(1) — Regardless of contract size within standard integer bounds, we execute one integer division, one modulo operation, and a fixed 12-iteration loop. (For arbitrarily huge multi-thousand-digit Python integers, dividing by 12 scales with the bit length O(log(total_cents)).)
  • Space: O(1) — Only two scalar integers (base_cents, remainder_cents) and the fixed 12-element output list are allocated.

Edge cases

  • Zero cents (total_cents == 0): base_cents = 0 and remainder_cents = 0, returning twelve 0s ([0, 0, ..., 0]), never [].
  • Sub-12 totals (e.g. total_cents == 7): base_cents = 0 and remainder_cents = 7, placing 1 cent in months 0..6 and 0 in months 7..11.
  • Exact multiple of 12 (e.g. total_cents == 3600): remainder_cents = 0, month_index < 0 never triggers, and all 12 months receive 300.
  • Largest possible remainder (total_cents % 12 == 11, e.g. 35): Months 0..10 receive 3 and only month 11 receives 2.
  • Large 64-bit+ totals (e.g. 10**18 + 7): Python's arbitrary-precision int keeps // and % exact without overflow or float precision loss.

Common mistakes

  • Writing <= instead of < (month_index <= remainder_cents): Because month_index starts at 0, <= awards remainder_cents + 1 extra pennies instead of remainder_cents, pushing the annual sum to total_cents + 1 (even when remainder_cents == 0).
  • Placing the entire remainder onto month 0: Returning [base + remainder, base, ..., base] preserves the sum, but breaks the balanced-spread requirement whenever remainder >= 2 (turning 50 cents into [6, 4, 4, ...] instead of [5, 5, 4, ...]).
  • Rounding total_cents / 12 per month: Identical per-month rounding loses or invents up to 6 cents across the year (50 becomes twelve 4s summing to 48, while 55 becomes twelve 5s summing to 60).
  • Returning fewer than 12 items when total_cents < 12: Callers always expect one entry per calendar month.

Alternative approaches

  • Slice multiplication and concatenation: [base_cents + 1] * remainder_cents + [base_cents] * (12 - remainder_cents) builds the same 12-element list in O(1) time and space; the explicit loop simply highlights the index boundary step by step.
  • Built-in divmod(total_cents, 12): Computes (base_cents, remainder_cents) in one call with identical runtime and memory.

Follow-up questions

  • What adjustment is needed if leftover cents must be assigned to the final months of the year rather than the opening months? Swap the single loop check if month_index < remainder_cents: to if month_index >= 12 - remainder_cents:. Indices 0 through 11 - remainder_cents stay at base_cents while the trailing remainder_cents months (12 - remainder_cents through 11) receive base_cents + 1, so total_cents = 50 yields [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5].
  • Suppose a contract is active only between given start and end dates. How would you prorate the cent total across months by active calendar days without losing pennies? First compute active days d_i inside each month i by intersecting [start_date, end_date] with that month's calendar span (via calendar.monthrange(year, month)[1] so leap Februaries and 30/31-day months are exact) and sum total_days = sum(d_i). Next apply the largest-remainder method (also known as Hamilton's method, a fair integer apportionment rule that assigns each bucket its integer floor share first and awards leftover pennies one each to buckets with the largest fractional remainders): assign month i a floor share (total_cents * d_i) // total_days, rank months by (total_cents * d_i) % total_days descending (breaking ties by earlier month index), and add +1 cent to the top total_cents - sum(floors) months using pure integer arithmetic.
  • How do the runtime and memory usage of this approach scale, and is any further asymptotic improvement possible? Both time and space are already O(1) for a fixed 12-month calendar (O(m) when generalized to m billing periods, which is optimal whenever the caller requires a materialized m-element list). If m grew to millions of fine-grained intervals, the only way to avoid O(m) memory would be returning a lazy query object share_at(i) that evaluates base_cents + (1 if i < remainder_cents else 0) on demand in O(1) time and O(1) space.

Follow-up questions

Similar questions

More Rillet interview questions

All 1 Rillet questions →