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:
- Exact conservation: Summing the
12returned integers equalstotal_centswith zero pennies lost or created. - Balanced spread: Monthly values differ by at most
1cent — every entry is eithertotal_cents // 12or(total_cents // 12) + 1. - Earliest-month priority: Whenever
total_centsis not a multiple of12, ther = total_cents % 12leftover cents are placed1cent apiece onto the firstrmonths (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
12containing exactintvalues (avoid floating-point rounding).
Step-by-step walkthrough
Restate the problem and check the rules
Given a non-negative integer
total_centsrepresenting a full year's contract revenue in cents, we must return a list of 12 integers (months0through11) satisfying three accounting invariants:- Exact conservation: All 12 monthly amounts add up to
total_centswith zero pennies lost or gained. - Balanced spread: Every month receives either
total_cents // 12or(total_cents // 12) + 1. - Front-loaded leftover: Any leftover cents after dividing by
12go1cent apiece to the earliest months (0, 1, ..., remainder - 1).
- Exact conservation: All 12 monthly amounts add up to
Why floating-point division fails for money
Dividing with
/(total_cents / 12) and callinground()fails for two separate reasons:- Sums drift away from the total:
50 / 12is4.1666..., which rounds down to4for every single month — summing to48instead of50and losing two cents! - Large integers lose precision: Standard 64-bit floats (
float) only represent every integer without gaps up to2^53(around9 * 10^15). Above that threshold,float(10**18 + 7)silently rounds to10**18before the division even begins.
Financial ledgers avoid floats entirely by storing money as integer cents and splitting amounts via integer quotients and remainders.
- Sums drift away from the total:
Key idea: baseline quotient plus leftover remainder
Every non-negative integer
total_centsdecomposes 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):- First, assign
base_centsto every one of the 12 months, accounting for12 * base_centscents. - Next,
remainder_centsindividual pennies (0through11) remain. Becauseremainder_cents < 12, no month ever receives two extra pennies — we simply add+1to each of the firstremainder_centsmonths (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: indices0throughremainder_cents - 1cover preciselyremainder_centsmonths (and whenremainder_cents == 0,month_index < 0isFalsefor every index).- First, assign
Code the 12-month loop
We step
month_indexacross0 .. 11, appendingbase_cents + 1whenevermonth_index < remainder_centsandbase_centsotherwise.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 monthsTrace the examples and boundary cases
Let's verify our formula across all three examples from
statement.mdplus35and0: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] 0Every case produces 12 integers, keeps max-minus-min at most
1, front-loads extra pennies from index0, and sums back tototal_cents.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 fixed12-iteration loop. (For arbitrarily huge multi-thousand-digit Python integers, dividing by12scales with the bit lengthO(log(total_cents)).) - Space:
O(1)— Only two scalar integers (base_cents,remainder_cents) and the fixed12-element output list are allocated.
Edge cases
- Zero cents (
total_cents == 0):base_cents = 0andremainder_cents = 0, returning twelve0s ([0, 0, ..., 0]), never[]. - Sub-12 totals (e.g.
total_cents == 7):base_cents = 0andremainder_cents = 7, placing1cent in months0..6and0in months7..11. - Exact multiple of 12 (e.g.
total_cents == 3600):remainder_cents = 0,month_index < 0never triggers, and all 12 months receive300. - Largest possible remainder (
total_cents % 12 == 11, e.g.35): Months0..10receive3and only month11receives2. - Large 64-bit+ totals (e.g.
10**18 + 7): Python's arbitrary-precisionintkeeps//and%exact without overflow or float precision loss.
Common mistakes
- Writing
<=instead of<(month_index <= remainder_cents): Becausemonth_indexstarts at0,<=awardsremainder_cents + 1extra pennies instead ofremainder_cents, pushing the annual sum tototal_cents + 1(even whenremainder_cents == 0). - Placing the entire remainder onto month
0: Returning[base + remainder, base, ..., base]preserves the sum, but breaks the balanced-spread requirement wheneverremainder >= 2(turning50cents into[6, 4, 4, ...]instead of[5, 5, 4, ...]). - Rounding
total_cents / 12per month: Identical per-month rounding loses or invents up to6cents across the year (50becomes twelve4s summing to48, while55becomes twelve5s summing to60). - 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 same12-element list inO(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:toif month_index >= 12 - remainder_cents:. Indices0through11 - remainder_centsstay atbase_centswhile the trailingremainder_centsmonths (12 - remainder_centsthrough11) receivebase_cents + 1, sototal_cents = 50yields[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_iinside each monthiby intersecting[start_date, end_date]with that month's calendar span (viacalendar.monthrange(year, month)[1]so leap Februaries and 30/31-day months are exact) and sumtotal_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 monthia floor share(total_cents * d_i) // total_days, rank months by(total_cents * d_i) % total_daysdescending (breaking ties by earlier month index), and add+1cent to the toptotal_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 tombilling periods, which is optimal whenever the caller requires a materializedm-element list). Ifmgrew to millions of fine-grained intervals, the only way to avoidO(m)memory would be returning a lazy query objectshare_at(i)that evaluatesbase_cents + (1 if i < remainder_cents else 0)on demand inO(1)time andO(1)space.
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?
- 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?
- How do the runtime and memory usage of this approach scale, and is any further asymptotic improvement possible?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array