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 i applies decimal rate solely 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 when brackets is empty) incur 0.0 tax.

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.0
  • 0.0 <= income <= 10^12
  • Both lower_cutoff and income may be integers or floating-point values; answers within 10^-6 relative error are accepted.

Step-by-step walkthrough

  1. Restate the problem: how marginal tiers slice earnings

    We receive brackets, an ascending list of (lower_cutoff, rate) pairs, along with gross income. Tier i applies its decimal rate strictly 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 a float.

    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.0
    

    Two rules from the examples are especially important: - Only the dollars inside a tier pay that tier's rate: earning $30,000 does not mean paying 18% 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)] with income = 8000 leaves the first $2,000 untaxed and taxes only the $6,000 slice in [2000, 8000) at 12% for $720.0.

  2. Why dollar-by-dollar simulation is not enough

    A literal simulation loops unit from 0 to income - 1, finds which tier unit belongs to, and adds that tier's rate. That approach has two flaws:

    1. Runtime depends on income (O(income * K)): An income of $10,000,000,000 would run ten billion loop iterations to process three tiers.
    2. Fails on fractional values: Notice the signature takes float cutoffs and float income (for example, cutoff = 100.5 and income = 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.

  3. Key idea: measure the overlap with each bracket interval

    Tier i covers 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_cutoff
    

    Cases 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 at taxable_top = min(income, next_cutoff). - On the last tier, there is no upper cutoff, so taxable_top = income. - The tax contributed by tier i is (taxable_top - lower_cutoff) * rate.

    And because brackets is ordered by ascending lower_cutoff, the very first tier with income <= lower_cutoff tells us no later tier can hold any earnings either, so we break immediately.

  4. Handle the top unbounded bracket safely

    Reading brackets[i + 1][0] unconditionally would raise IndexError on the last tier (i == num_brackets - 1). Checking i + 1 < num_brackets picks min(income, next_cutoff) for bounded tiers and income directly 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 = income
    
  5. Loop over brackets and accumulate total tax

    Putting the pieces together inside calculate_progressive_tax, we start total_tax = 0.0 (ensuring a float return even when brackets is empty or income sits below the opening cutoff) and sweep through brackets once:

    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
    
  6. Trace 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.0
    
  7. Complete 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 the K tiers at most once from lowest cutoff to highest, doing O(1) comparisons and arithmetic per tier, and stopping early as soon as income <= lower_cutoff. Runtime is completely independent of the magnitude of income.
  • Space: O(1). We only maintain total_tax and 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 below 2000 are never covered by any tier and owe 0.0; an income of 8000 taxes only 8000 - 2000 = 6000.
  • Income equal to an exact cutoff (income == 12000): Tier 0 taxes 12000 - 0 = 12000, and on Tier 1 the check income <= lower_cutoff (12000 <= 12000) triggers break cleanly without adding a zero or negative slice.
  • Income above the highest cutoff (income = 65000 in Example 3): On i == num_brackets - 1, taxable_top becomes income, taxing all dollars above 40000 at 28%.
  • Zero income or empty brackets: Returns 0.0 immediately.
  • Middle 0% tax band ([(0, 0.1), (1000, 0.0), (10000, 0.2)]): Adds 0.0 for [1000, 10000) while still capping the 10% band at 1000.
  • Floating-point cutoffs and incomes (100.5, 200.5): Handled naturally by subtraction; callers comparing floats should use a small relative tolerance (such as 1e-6) because binary floating point cannot represent 0.1 or 0.08 exactly.

Common mistakes

  • Taxing the entire income at the highest reached tier's rate: Treats marginal tiers as a flat cliff, failing Example 2 (5400 instead of 4200).
  • Assuming brackets[0][0] is always 0: Hard-coding prev_cutoff = 0 taxes the untaxed [0, 2000) band in Example 4 (960 instead of 720).
  • Indexing brackets[i + 1] without checking i + 1 < len(brackets): Crashes with IndexError whenever income reaches the top tier.
  • Capping or ignoring income above the last cutoff: Treating the last tier as having width 0 fails Example 3 (6000 instead of 13000).
  • 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 to lower_i, computed in one O(K) pass). For each query income, run binary search (bisect_right — repeatedly halving the sorted cutoff array to locate the highest tier with lower_i <= income in O(log K) time) and return 0.0 if i < 0, or base_tax[i] + (income - lower_i) * rate_i in O(1) arithmetic.
  • How do production payroll and brokerage systems avoid binary floating-point rounding drift? IEEE-754 binary float values cannot represent 0.08 or 0.18 exactly (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, where 15.25% = 1525 out of 10,000) or use decimal.Decimal with 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 slope 1 - rate_i inside tier i. Precompute net_at_cutoff[i] = lower_i - base_tax[i], find the last tier with net_at_cutoff[i] <= target_net, and solve the linear segment gross = lower_i + (target_net - net_at_cutoff[i]) / (1.0 - rate_i) (or return target_net directly when it sits below brackets[0][0]).

Follow-up questions

Similar questions

More Interactive Brokers interview questions

All 3 Interactive Brokers questions →