Marginal Tax Across Income Tiers
Easy · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given a tiered schedule of marginal tax rates and a taxpayer's gross income, compute the total tax owed.
The schedule brackets contains (lower_cutoff, rate) pairs arranged in strictly increasing order of lower_cutoff:
- Band
iapplies decimalratesolely to earnings falling inside[lower_cutoff_i, lower_cutoff_{i+1}). - The final band has no upper ceiling and taxes all earnings above its
lower_cutoff. - Any earnings at or below
brackets[0][0](or all earnings whenbracketsis empty) incur0.0tax.
Return the total tax owed as a float.
def calculate_progressive_tax(brackets: list[tuple[float, float]], income: float) -> float:
pass
Examples
Example 1
Input: brackets = [(0, 0.08), (12000, 0.18), (40000, 0.28)], income = 7500
Output: 600.0
Walk-through: All 7500 falls inside the opening band [0, 12000) at 8%, producing 7500 * 0.08 = 600.0.
Example 2
Input: brackets = [(0, 0.08), (12000, 0.18), (40000, 0.28)], income = 30000
Output: 4200.0
Walk-through: The first 12000 in [0, 12000) owes 12000 * 0.08 = 960.0, and the remaining 18000 in [12000, 30000) owes 18000 * 0.18 = 3240.0, totaling 960.0 + 3240.0 = 4200.0.
Example 3
Input: brackets = [(0, 0.08), (12000, 0.18), (40000, 0.28)], income = 65000
Output: 13000.0
Walk-through: Band 0 taxes 12000 * 0.08 = 960.0, Band 1 taxes (40000 - 12000) * 0.18 = 5040.0, and the unbounded top band taxes (65000 - 40000) * 0.28 = 7000.0, summing to 13000.0.
Example 4
Input: brackets = [(2000, 0.12), (8000, 0.20), (25000, 0.30)], income = 8000
Output: 720.0
Walk-through: Earnings in [0, 2000) sit below the opening threshold 2000 and owe 0.0. Only the 6000 slice inside [2000, 8000) is taxed at 12% (6000 * 0.12 = 720.0), and nothing reaches 8000 or higher.
Constraints
0 <= len(brackets) <= 10^4- Cutoffs are non-negative and strictly increasing (
0.0 <= lower_cutoff_0 < lower_cutoff_1 < ...). 0.0 <= rate <= 1.00.0 <= income <= 10^12- Both
lower_cutoffandincomemay be integers or floating-point values; answers within10^-6relative error are accepted.
Step-by-step walkthrough
Restate the problem: how marginal tiers slice earnings
We receive
brackets, an ascending list of(lower_cutoff, rate)pairs, along with grossincome. Tieriapplies its decimalratestrictly to earnings falling inside[lower_cutoff_i, lower_cutoff_{i+1}), while the final tier has no ceiling. We return the total tax owed as afloat.Example 2: brackets = [(0, 0.08), (12000, 0.18), (40000, 0.28)], income = 30000 Income line: 0 --------- 12000 ------------- 30000 -------- 40000 -----> | $12,000 | $18,000 | ($0 here: income stops at 30,000) | @ 8% | @ 18% | @ 28% Tax per band: $960 + $3,240 + $0 = $4,200.0Two rules from the examples are especially important: - Only the dollars inside a tier pay that tier's rate: earning
$30,000does not mean paying18%on all$30,000. - Earnings below the opening cutoff are untaxed (0%): in Example 4,brackets = [(2000, 0.12), (8000, 0.20), (25000, 0.30)]withincome = 8000leaves the first$2,000untaxed and taxes only the$6,000slice in[2000, 8000)at12%for$720.0.Why dollar-by-dollar simulation is not enough
A literal simulation loops
unitfrom0toincome - 1, finds which tierunitbelongs to, and adds that tier's rate. That approach has two flaws:- Runtime depends on
income(O(income * K)): An income of$10,000,000,000would run ten billion loop iterations to process three tiers. - Fails on fractional values: Notice the signature takes
floatcutoffs andfloatincome (for example,cutoff = 100.5andincome = 200.5), which cannot be stepped through unit by unit.
Instead, we can compute the exact width of earnings inside each tier with one subtraction.
- Runtime depends on
Key idea: measure the overlap with each bracket interval
Tier
icovers the interval[lower_cutoff, next_cutoff)(or[lower_cutoff, infinity)on the top tier). How much of[0, income]lands inside that interval?Case A: income <= lower_cutoff Case B: lower_cutoff < income < next_cutoff 0 ----- income ... [lower --- next) 0 --------- [lower --- income --- next) Overlap width = 0 (and all later Overlap width = income - lower_cutoff tiers are empty too -> break!) Case C: income >= next_cutoff 0 --------- [lower --------- next) ... income Overlap width = next_cutoff - lower_cutoffCases B and C combine into one clean formula whenever
income > lower_cutoff: - On any tier before the last (i + 1 < num_brackets), the slice ends attaxable_top = min(income, next_cutoff). - On the last tier, there is no upper cutoff, sotaxable_top = income. - The tax contributed by tieriis(taxable_top - lower_cutoff) * rate.And because
bracketsis ordered by ascendinglower_cutoff, the very first tier withincome <= lower_cutofftells us no later tier can hold any earnings either, so webreakimmediately.Handle the top unbounded bracket safely
Reading
brackets[i + 1][0]unconditionally would raiseIndexErroron the last tier (i == num_brackets - 1). Checkingi + 1 < num_bracketspicksmin(income, next_cutoff)for bounded tiers andincomedirectly for the top tier:# Cap this bracket's slice at the next cutoff, or at `income` on the top unbounded bracket. if i + 1 < num_brackets: next_cutoff = brackets[i + 1][0] taxable_top = min(income, next_cutoff) else: taxable_top = incomeLoop over brackets and accumulate total tax
Putting the pieces together inside
calculate_progressive_tax, we starttotal_tax = 0.0(ensuring afloatreturn even whenbracketsis empty orincomesits below the opening cutoff) and sweep throughbracketsonce:def calculate_progressive_tax(brackets: list[tuple[float, float]], income: float) -> float: # brackets: sorted (lower_cutoff, rate) pairs; bracket i taxes [lower_i, lower_{i+1}). total_tax = 0.0 num_brackets = len(brackets) for i in range(num_brackets): lower_cutoff, rate = brackets[i] # Stop once income does not exceed lower_cutoff: the slice here has width 0, # and because brackets are sorted, every later cutoff is at least as high. if income <= lower_cutoff: break # Cap this bracket's slice at the next cutoff, or at `income` on the top unbounded bracket. if i + 1 < num_brackets: next_cutoff = brackets[i + 1][0] taxable_top = min(income, next_cutoff) else: taxable_top = income # Tax only the marginal dollars sitting inside [lower_cutoff, taxable_top). taxable_slice = taxable_top - lower_cutoff total_tax += taxable_slice * rate return total_taxTrace Examples 3 and 4 step by step
Example 3: brackets = [(0, 0.08), (12000, 0.18), (40000, 0.28)], income = 65000 i=0: lower=0, next=12000 -> top=min(65000, 12000)=12000 -> slice=12000 * 0.08 = 960.0 i=1: lower=12000, next=40000 -> top=min(65000, 40000)=40000 -> slice=28000 * 0.18 = 5040.0 i=2: lower=40000, (last) -> top=65000 -> slice=25000 * 0.28 = 7000.0 total_tax = 960.0 + 5040.0 + 7000.0 = 13000.0 Example 4: brackets = [(2000, 0.12), (8000, 0.20), (25000, 0.30)], income = 8000 (0 .. 2000 sits below brackets[0][0], so it is never touched) i=0: lower=2000, next=8000 -> top=min(8000, 8000)=8000 -> slice=(8000 - 2000) * 0.12 = 720.0 i=1: lower=8000 -> income <= lower_cutoff (8000 <= 8000) -> break! total_tax = 720.0Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def calculate_progressive_tax(brackets: list[tuple[float, float]], income: float) -> float: # brackets: sorted (lower_cutoff, rate) pairs; bracket i taxes [lower_i, lower_{i+1}). total_tax = 0.0 num_brackets = len(brackets) for i in range(num_brackets): lower_cutoff, rate = brackets[i] # Stop once income does not exceed lower_cutoff: the slice here has width 0, # and because brackets are sorted, every later cutoff is at least as high. if income <= lower_cutoff: break # Cap this bracket's slice at the next cutoff, or at `income` on the top unbounded bracket. if i + 1 < num_brackets: next_cutoff = brackets[i + 1][0] taxable_top = min(income, next_cutoff) else: taxable_top = income # Tax only the marginal dollars sitting inside [lower_cutoff, taxable_top). taxable_slice = taxable_top - lower_cutoff total_tax += taxable_slice * rate return total_tax✅ Submit now — all tests should pass.
Intuition & how it works
Picture a row of measuring pitchers lined up from left to right, each with a different tax percentage printed on its side. When you pour your earnings in, you completely fill the first pitcher before a single drop spills into the second pitcher, and only the liquid inside each pitcher pays that pitcher's sticker percentage. That sticker is a marginal tax rate (the percentage charged solely on the slice of earnings inside one specific tier, rather than across all earnings).
Why do naive approaches fail? Multiplying gross income by the highest reached tier's rate confuses a marginal schedule with a flat cliff — on $30,000 in Example 2, 30000 * 0.18 = 5400 overcharges by $1,200 because the opening $12,000 only owes 8%. On the other hand, looping one dollar at a time (for dollar in range(income)) takes O(income) work that stalls on large incomes and cannot handle fractional values like $200.50. Measuring the interval overlap (min(income, next_cutoff) - lower_cutoff) computes each tier's exact slice in O(1) arithmetic.
Here is a concrete trace of Example 2 (brackets = [(0, 0.08), (12000, 0.18), (40000, 0.28)], income = 30000):
Tier 0 [0, 12000) @ 8%:
taxable_top = min(30000, 12000) = 12000
taxable_slice = 12000 - 0 = 12000 -> tax += 12000 * 0.08 = 960.0
Tier 1 [12000, 40000) @ 18%:
taxable_top = min(30000, 40000) = 30000
taxable_slice = 30000 - 12000 = 18000 -> tax += 18000 * 0.18 = 3240.0
Tier 2 [40000, inf) @ 28%:
income <= lower_cutoff (30000 <= 40000) -> break!
Total tax = 960.0 + 3240.0 = 4200.0
Complexity
Let K be the number of tiers in brackets.
- Time:
O(K). We scan theKtiers at most once from lowest cutoff to highest, doingO(1)comparisons and arithmetic per tier, and stopping early as soon asincome <= lower_cutoff. Runtime is completely independent of the magnitude ofincome. - Space:
O(1). We only maintaintotal_taxand a few scalar variables (lower_cutoff,rate,next_cutoff,taxable_top,taxable_slice), allocating no extra lists or dictionaries.
Edge cases
- First cutoff above zero (untaxed personal allowance): In Example 4 (
brackets[0] = (2000, 0.12)), earnings below2000are never covered by any tier and owe0.0; an income of8000taxes only8000 - 2000 = 6000. - Income equal to an exact cutoff (
income == 12000): Tier0taxes12000 - 0 = 12000, and on Tier1the checkincome <= lower_cutoff(12000 <= 12000) triggersbreakcleanly without adding a zero or negative slice. - Income above the highest cutoff (
income = 65000in Example 3): Oni == num_brackets - 1,taxable_topbecomesincome, taxing all dollars above40000at28%. - Zero income or empty
brackets: Returns0.0immediately. - Middle
0%tax band ([(0, 0.1), (1000, 0.0), (10000, 0.2)]): Adds0.0for[1000, 10000)while still capping the10%band at1000. - Floating-point cutoffs and incomes (
100.5,200.5): Handled naturally by subtraction; callers comparing floats should use a small relative tolerance (such as1e-6) because binary floating point cannot represent0.1or0.08exactly.
Common mistakes
- Taxing the entire income at the highest reached tier's rate: Treats marginal tiers as a flat cliff, failing Example 2 (
5400instead of4200). - Assuming
brackets[0][0]is always0: Hard-codingprev_cutoff = 0taxes the untaxed[0, 2000)band in Example 4 (960instead of720). - Indexing
brackets[i + 1]without checkingi + 1 < len(brackets): Crashes withIndexErrorwheneverincomereaches the top tier. - Capping or ignoring income above the last cutoff: Treating the last tier as having width
0fails Example 3 (6000instead of13000). - Rounding intermediate tier taxes: Rounding after every slice accumulates rounding drift; always sum exact values and round once at the very end if currency rounding is requested.
Follow-up questions
- How can you evaluate millions of income queries quickly against a fixed bracket schedule? Precompute a prefix sum array
base_tax[i](storing the cumulative tax owed on an income equal tolower_i, computed in oneO(K)pass). For each queryincome, run binary search (bisect_right— repeatedly halving the sorted cutoff array to locate the highest tier withlower_i <= incomeinO(log K)time) and return0.0ifi < 0, orbase_tax[i] + (income - lower_i) * rate_iinO(1)arithmetic. - How do production payroll and brokerage systems avoid binary floating-point rounding drift? IEEE-754 binary
floatvalues cannot represent0.08or0.18exactly (0.1 + 0.2 == 0.30000000000000004). Production financial engines store money in integer minor units (cents) and rates in integer basis points (hundredths of a percent, where15.25% = 1525out of10,000) or usedecimal.Decimalwith an explicit business rounding mode such as round-half-even (ROUND_HALF_EVEN) applied once at the end. - Given a target after-tax net payout, how would you invert the schedule to recover pre-tax gross income? Provided every marginal rate is strictly less than
1.0,net(gross) = gross - tax(gross)is strictly increasing and piecewise linear with slope1 - rate_iinside tieri. Precomputenet_at_cutoff[i] = lower_i - base_tax[i], find the last tier withnet_at_cutoff[i] <= target_net, and solve the linear segmentgross = lower_i + (target_net - net_at_cutoff[i]) / (1.0 - rate_i)(or returntarget_netdirectly when it sits belowbrackets[0][0]).
Follow-up questions
- How can you evaluate millions of income queries quickly against a fixed bracket schedule?
- How do production payroll and brokerage systems avoid binary floating-point rounding drift?
- Given a target after-tax net payout, how would you invert the schedule to recover pre-tax gross income?
Similar questions
- Progressive Marginal Tax Calculator
- 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