Progressive Marginal Tax Calculator
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Implement calculate_tax(income, brackets) to compute the marginal tax liability on a non-negative income across an ordered schedule of tax tiers.
Each element of brackets is a pair (ceiling, rate) ordered from smallest ceiling to largest ceiling:
- The first tier covers earnings from
0up toceiling_0at marginal multiplierrate_0. - Every later tier
icovers earnings from the preceding tier's ceilingceiling_{i-1}up toceiling_iat marginal multiplierrate_i. - Only dollars inside
[floor, ceiling)are multiplied by that tier'srate; moving into a higher tier never alters the multiplier applied to earlier dollars. - Only tiers explicitly listed in
bracketscollect tax. When the last tier has a finiteceilingandincomerises past it, any excess above that finalceilingincurs zero additional tax unless a catch-all tier(float('inf'), rate)appears at the end ofbrackets.
Return the total tax as a float (0.0 when income == 0 or brackets is empty).
def calculate_tax(income: float, brackets: List[Tuple[float, float]]) -> float:
Examples
Example 1
- Input:
income = 42000,brackets = [(15000, 0.12), (50000, 0.22)] - Output:
7740.0 - Explanation: Earnings in
[0, 15000)owe15000 * 0.12 = 1800.0. The remaining42000 - 15000 = 27000sit inside[15000, 50000)and owe27000 * 0.22 = 5940.0, totaling1800.0 + 5940.0 = 7740.0.
Example 2
- Input:
income = 8000,brackets = [(12000, 0.15)] - Output:
1200.0 - Explanation: All
8000fall below the12000ceiling of the lone tier, yielding8000 * 0.15 = 1200.0.
Example 3
- Input:
income = 0,brackets = [(15000, 0.12), (50000, 0.22), (float('inf'), 0.35)] - Output:
0.0 - Explanation: With zero earnings, every tier receives
0dollars and owes0.0.
Example 4
- Input:
income = 75000,brackets = [(15000, 0.12), (50000, 0.22)] - Output:
9500.0 - Explanation: Tier 1 collects
15000 * 0.12 = 1800.0and Tier 2 collects(50000 - 15000) * 0.22 = 7700.0. Because no unbounded top tier follows50000, the top25000is untaxed, giving1800.0 + 7700.0 = 9500.0.
Constraints
0 <= income <= 10^12(intorfloat)0 <= len(brackets) <= 10^5bracketsis sorted in non-decreasing order ofceiling, withceiling > 0(the finalceilingmay befloat('inf')).0.0 <= rate <= 1.0for every tier.
Step-by-step walkthrough
Understand marginal tiers and finite ceilings
We receive a non-negative
incomeand an ordered listbracketsof(ceiling, rate)pairs. Under marginal taxation, crossing into a steeper tier never raises the rate paid on earlier dollars. Instead, each tier owns a contiguous slice[tier_floor, ceiling)starting right where the prior tier ended:income = 42,000 across [(15000, 0.12), (50000, 0.22)]: 0 15,000 42,000 50,000 |---- 15,000 ----|---------- 27,000 ----------|...............| at 12% = 1,800.0 at 22% = 5,940.0 unreached room in tier 2 Total tax = 1,800.0 + 5,940.0 = 7,740.0Notice also the finite-table rule illustrated in Example 4 (
income = 75000with ceilings15000and50000returns9500.0): only tiers present inbracketscharge tax, while callers pass a trailing(float('inf'), rate)pair whenever unbounded top earnings should be taxed.Why unit-by-unit simulation fails
Stepping one dollar at a time from
1up toincomeand finding which tier owns each dollar breaks down for two reasons:- Runtime scales with dollar value: Earning
10^12would trigger a trillion iterations even whenbracketshas just two entries. - Fractional cents cannot be counted as integers: An
incomelike12345.50is a floating-point quantity, not an integer count of whole dollars.
Because every dollar inside
[tier_floor, ceiling)shares the exact samerate, we can compute the entire tier's contribution with a single subtraction and multiplication.- Runtime scales with dollar value: Earning
Measure the overlap inside one tier
Maintain
tier_floor(initialized to0.0) as the start of the current tier[tier_floor, ceiling). Wheneverincomereaches pasttier_floor, two cases arise:Case A: income continues past ceiling Case B: income stops inside the tier tier_floor ceiling income tier_floor income ceiling |==================|-----------> |=================|............| <-- taxed_dollars -> <- taxed_dollars -> tier_top = ceiling tier_top = incomeIn both cases, the upper endpoint of taxed money inside this tier is
tier_top = min(income, ceiling), and the slice width istaxed_dollars = tier_top - tier_floor.Halt early once earnings are exhausted
Because
bracketsis ordered in non-decreasingceilingorder,tier_floornever shrinks. The momentincome <= tier_floor, zero dollars lie abovetier_floorin this tier or any later tier, so we canbreakimmediately.Checking
income <= tier_floorbefore subtracting gives two clean guarantees:- Whenever we compute
taxed_dollars, bothincome > tier_floorandceiling >= tier_floorhold, sotaxed_dollars >= 0.0. - After visiting an unbounded tier
(float('inf'), rate),tier_floorbecomesinf; if any extra tuple followed it,income <= infimmediately breaks rather than evaluatingincome - inf = -inf.
total_tax = 0.0 tier_floor = 0.0 for ceiling, rate in brackets: if income <= tier_floor: break tier_top = min(income, ceiling) taxed_dollars = tier_top - tier_floor total_tax += taxed_dollars * rate tier_floor = ceiling- Whenever we compute
Trace Example 1 and Example 4
Let's walk through
brackets = [(15000, 0.12), (50000, 0.22)]for bothincome = 42000(Example 1) andincome = 75000(Example 4):Example 1: income = 42000 Start: total_tax = 0.0, tier_floor = 0.0 Tier (15000, 0.12): 42000 <= 0.0 is False tier_top = min(42000, 15000) = 15000 taxed_dollars = 15000 - 0.0 = 15000.0 total_tax = 0.0 + 15000.0 * 0.12 = 1800.0 tier_floor = 15000 Tier (50000, 0.22): 42000 <= 15000 is False tier_top = min(42000, 50000) = 42000 taxed_dollars = 42000 - 15000 = 27000 total_tax = 1800.0 + 27000 * 0.22 = 7740.0 tier_floor = 50000 End of tiers -> return 7740.0 Example 4: income = 75000 Tier (15000, 0.12): taxed_dollars = 15000 -> +1800.0 (total_tax = 1800.0) Tier (50000, 0.22): tier_top = min(75000, 50000) = 50000 taxed_dollars = 50000 - 15000 = 35000 -> +7700.0 (total_tax = 9500.0) End of tiers (no inf tier supplied) -> return 9500.0Complete solution
Combining the loop, early exit, and boundary comments gives the full implementation.
from typing import Any, Dict, List, Optional, Set, Tuple def calculate_tax(income: float, brackets: List[Tuple[float, float]]) -> float: # total_tax: running marginal tax accumulated across visited tiers (e.g. 7740.0) total_tax = 0.0 # tier_floor: lower boundary of the current tier [tier_floor, ceiling), starting at 0.0 tier_floor = 0.0 # Phase 1: Scan tiers in non-decreasing ceiling order, taxing the overlap with [0, income). for ceiling, rate in brackets: # Halt once earnings no longer reach above tier_floor. Checking <= covers income == tier_floor # (zero dollars in this tier) and avoids evaluating income - inf after an unbounded tier. if income <= tier_floor: break # Phase 2: Clamp earnings to this tier's ceiling and tax only the width above tier_floor. tier_top = min(income, ceiling) taxed_dollars = tier_top - tier_floor total_tax += taxed_dollars * rate # Shift the floor up so the next tier begins directly at this tier's ceiling. tier_floor = ceiling # Phase 3: Return accumulated tax. As shown in Example 4, earnings above a finite final ceiling # owe nothing unless the caller supplies a trailing (float('inf'), rate) tier. return total_tax✅ Submit now — all tests should pass.
Intuition & how it works
Picture marginal tax tiers — a pricing structure where each dollar slice is charged only its own tier's rate without re-pricing earlier dollars — as a row of measuring cups placed side by side. Pouring 42,000 in from the left fills the first cup of capacity 15,000 (charged at 12%), and only the 27,000 spillover lands in the second cup spanning 15,000 to 50,000 (charged at 22%). Every cup simply multiplies the volume that actually lands inside it by its own rate.
Why do naive strategies fail? Multiplying the full 42,000 by 22% (9,240.0) computes a flat tax rather than a marginal schedule, overcharging the initial 15,000. Looping one dollar at a time from 1 up to income takes O(income) time — far too slow for multi-million-dollar figures — and cannot handle fractional amounts like 12345.50. Instead, computing the interval overlap — the shared span between [0, income) and [tier_floor, ceiling) — processes each tier in O(1) arithmetic for any integer or fractional income.
Let's trace income = 42000 on brackets = [(15000, 0.12), (50000, 0.22)]:
Start: total_tax = 0.0, tier_floor = 0.0
1. Tier (15000, 0.12):
tier_top = min(42000, 15000) = 15000
taxed_dollars = 15000 - 0.0 = 15000.0
total_tax += 15000.0 * 0.12 -> 1800.0
tier_floor = 15000
2. Tier (50000, 0.22):
tier_top = min(42000, 50000) = 42000
taxed_dollars = 42000 - 15000 = 27000
total_tax += 27000 * 0.22 -> 7740.0
tier_floor = 50000
End of tiers -> return 7740.0
Complexity
Let k be len(brackets).
- Time:
O(k). We inspect each of thektiers at most once, doing constant-time arithmetic (min, subtraction, multiplication, addition) per tier and breaking early as soon asincome <= tier_floor. - Space:
O(1). Only four scalar variables (total_tax,tier_floor,tier_top,taxed_dollars) are kept in memory regardless ofkorincome.
Edge cases
- Zero earnings (
income = 0): On the very first tier,0 <= 0.0evaluates toTrue, breaking immediately and returning0.0. - Empty
brackets([]): Theforloop performs zero iterations and returns0.0. - Earnings equal to a ceiling (
income = 15000): Tier 1 taxes all15000, advancestier_floorto15000, and Tier 2 exits immediately on15000 <= 15000. - Earnings above the last finite ceiling (
income = 75000, last ceiling50000): Taxes up to50000(9500.0), matching Example 4. When a trailing(float('inf'), 0.35)catch-all tier is present,min(income, float('inf'))equalsincomeand taxes all remaining dollars at0.35. - Repeated ceilings (
[(10000, 0.1), (10000, 0.9)]): The second tier computesmin(income, 10000) - 10000 = 0, adding0.0without special branching. - Boundary rates (
0.0or1.0) and cents (12345.5): Handled naturally by standard floating-point arithmetic.
Common mistakes
- Charging a flat rate instead of marginal slices: Multiplying
42,000 * 0.22gives9,240.0instead of7,740.0because the first15,000should only pay12%. - Using
ceiling - tier_floorwithoutmin(income, ceiling): Bills the full capacity of the highest reached tier even whenincomestops partway inside it. - Forgetting
tier_floor = ceiling: Measuring every tier from0double-counts lower earnings across multiple tiers. - Inventing an implicit top bracket: Charging
last_rateonincome - tier_floorafter the loop fails Example 4 (15,000instead of9,500.0), where only listed tiers apply. - Rounding per tier: Rounding after every tier accumulates cent-level drift; when currency rounding is requested, round once at the end.
Alternative approaches
- Prefix tax totals + binary search (
O(log k)per query): A prefix sum (an array storing cumulative full-tier taxes for tiers0..i) paired with binary search (halving the sorted ceiling array viabisectto find the active tier inO(log k)comparisons) computes all completed tiers inO(1)plus one partial slice. Building the table takesO(k)time and space up front and speeds up batch runs over millions of taxpayers sharing one fixed schedule.
Follow-up questions
- Suppose the schedule gives each tier's width (such as [15000, 35000, 60000]) alongside a parallel list of rates instead of cumulative ceilings—how would your code adapt? First confirm whether those numbers are cumulative ceilings or marginal widths (the dollar capacity of each individual bucket: first
15,000, next35,000up to50,000, next60,000up to110,000). For cumulative ceilings, iterate overzip(widths, rates)directly (appending(float('inf'), rates[-1])ifrateshas one extra catch-all rate). For marginal widths, trackremaining = incomeand on each(width, rate)pair taxslice_amt = min(remaining, width), subtractremaining -= slice_amt, and stop onceremaining <= 0. - If earnings arrive incrementally as an ongoing sequence of payouts rather than one annual figure, how can you emit updated tax totals efficiently? Wrap the state in a small class holding
cumulative_income,cumulative_tax, and an indextier_idxpointing to the first unfinished tier. When a positive payoutdeltaarrives, advance fromcumulative_incometowardcumulative_income + delta, taxing each slice againstbrackets[tier_idx]and incrementingtier_idxonly whencumulative_incomehits that tier'sceiling. Becausetier_idxonly moves rightward acrossktiers, handlingmpayouts takesO(m + k)total work instead of re-scanning allktiers on every payout (O(m * k)). - How would you eliminate binary floating-point rounding drift when computing exact cent-level tax liabilities? IEEE-754 binary floats cannot represent most decimal fractions exactly (for example,
0.1 + 0.2evaluates to0.30000000000000004). In accounting code, either represent earnings and rates with Python'sdecimal.Decimalconstructed from strings (Decimal("0.12")), or work purely in exact integers using integer cents ($1 = 100cents) and basis points (units where1basis point is0.01%, or1 / 10,000). Accumulateslice_cents * rate_bpsin exact integer arithmetic across all tiers and divide by10,000once at the end under a specified rounding policy such asROUND_HALF_UP.
Follow-up questions
- Suppose the schedule gives each tier's width (such as [15000, 35000, 60000]) alongside a parallel list of rates instead of cumulative ceilings—how would your code adapt?
- If earnings arrive incrementally as an ongoing sequence of payouts rather than one annual figure, how can you emit updated tax totals efficiently?
- How would you eliminate binary floating-point rounding drift when computing exact cent-level tax liabilities?
Similar questions
- Marginal Tax Across Income Tiers
- Minimum Schedule Days With Cooldown
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance