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 0 up to ceiling_0 at marginal multiplier rate_0.
  • Every later tier i covers earnings from the preceding tier's ceiling ceiling_{i-1} up to ceiling_i at marginal multiplier rate_i.
  • Only dollars inside [floor, ceiling) are multiplied by that tier's rate; moving into a higher tier never alters the multiplier applied to earlier dollars.
  • Only tiers explicitly listed in brackets collect tax. When the last tier has a finite ceiling and income rises past it, any excess above that final ceiling incurs zero additional tax unless a catch-all tier (float('inf'), rate) appears at the end of brackets.

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) owe 15000 * 0.12 = 1800.0. The remaining 42000 - 15000 = 27000 sit inside [15000, 50000) and owe 27000 * 0.22 = 5940.0, totaling 1800.0 + 5940.0 = 7740.0.

Example 2

  • Input: income = 8000, brackets = [(12000, 0.15)]
  • Output: 1200.0
  • Explanation: All 8000 fall below the 12000 ceiling of the lone tier, yielding 8000 * 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 0 dollars and owes 0.0.

Example 4

  • Input: income = 75000, brackets = [(15000, 0.12), (50000, 0.22)]
  • Output: 9500.0
  • Explanation: Tier 1 collects 15000 * 0.12 = 1800.0 and Tier 2 collects (50000 - 15000) * 0.22 = 7700.0. Because no unbounded top tier follows 50000, the top 25000 is untaxed, giving 1800.0 + 7700.0 = 9500.0.

Constraints

  • 0 <= income <= 10^12 (int or float)
  • 0 <= len(brackets) <= 10^5
  • brackets is sorted in non-decreasing order of ceiling, with ceiling > 0 (the final ceiling may be float('inf')).
  • 0.0 <= rate <= 1.0 for every tier.

Step-by-step walkthrough

  1. Understand marginal tiers and finite ceilings

    We receive a non-negative income and an ordered list brackets of (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.0
    

    Notice also the finite-table rule illustrated in Example 4 (income = 75000 with ceilings 15000 and 50000 returns 9500.0): only tiers present in brackets charge tax, while callers pass a trailing (float('inf'), rate) pair whenever unbounded top earnings should be taxed.

  2. Why unit-by-unit simulation fails

    Stepping one dollar at a time from 1 up to income and finding which tier owns each dollar breaks down for two reasons:

    • Runtime scales with dollar value: Earning 10^12 would trigger a trillion iterations even when brackets has just two entries.
    • Fractional cents cannot be counted as integers: An income like 12345.50 is a floating-point quantity, not an integer count of whole dollars.

    Because every dollar inside [tier_floor, ceiling) shares the exact same rate, we can compute the entire tier's contribution with a single subtraction and multiplication.

  3. Measure the overlap inside one tier

    Maintain tier_floor (initialized to 0.0) as the start of the current tier [tier_floor, ceiling). Whenever income reaches past tier_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 = income
    

    In both cases, the upper endpoint of taxed money inside this tier is tier_top = min(income, ceiling), and the slice width is taxed_dollars = tier_top - tier_floor.

  4. Halt early once earnings are exhausted

    Because brackets is ordered in non-decreasing ceiling order, tier_floor never shrinks. The moment income <= tier_floor, zero dollars lie above tier_floor in this tier or any later tier, so we can break immediately.

    Checking income <= tier_floor before subtracting gives two clean guarantees:

    1. Whenever we compute taxed_dollars, both income > tier_floor and ceiling >= tier_floor hold, so taxed_dollars >= 0.0.
    2. After visiting an unbounded tier (float('inf'), rate), tier_floor becomes inf; if any extra tuple followed it, income <= inf immediately breaks rather than evaluating income - 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
    
  5. Trace Example 1 and Example 4

    Let's walk through brackets = [(15000, 0.12), (50000, 0.22)] for both income = 42000 (Example 1) and income = 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.0
    
  6. Complete 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 the k tiers at most once, doing constant-time arithmetic (min, subtraction, multiplication, addition) per tier and breaking early as soon as income <= tier_floor.
  • Space: O(1). Only four scalar variables (total_tax, tier_floor, tier_top, taxed_dollars) are kept in memory regardless of k or income.

Edge cases

  • Zero earnings (income = 0): On the very first tier, 0 <= 0.0 evaluates to True, breaking immediately and returning 0.0.
  • Empty brackets ([]): The for loop performs zero iterations and returns 0.0.
  • Earnings equal to a ceiling (income = 15000): Tier 1 taxes all 15000, advances tier_floor to 15000, and Tier 2 exits immediately on 15000 <= 15000.
  • Earnings above the last finite ceiling (income = 75000, last ceiling 50000): Taxes up to 50000 (9500.0), matching Example 4. When a trailing (float('inf'), 0.35) catch-all tier is present, min(income, float('inf')) equals income and taxes all remaining dollars at 0.35.
  • Repeated ceilings ([(10000, 0.1), (10000, 0.9)]): The second tier computes min(income, 10000) - 10000 = 0, adding 0.0 without special branching.
  • Boundary rates (0.0 or 1.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.22 gives 9,240.0 instead of 7,740.0 because the first 15,000 should only pay 12%.
  • Using ceiling - tier_floor without min(income, ceiling): Bills the full capacity of the highest reached tier even when income stops partway inside it.
  • Forgetting tier_floor = ceiling: Measuring every tier from 0 double-counts lower earnings across multiple tiers.
  • Inventing an implicit top bracket: Charging last_rate on income - tier_floor after the loop fails Example 4 (15,000 instead of 9,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 tiers 0..i) paired with binary search (halving the sorted ceiling array via bisect to find the active tier in O(log k) comparisons) computes all completed tiers in O(1) plus one partial slice. Building the table takes O(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, next 35,000 up to 50,000, next 60,000 up to 110,000). For cumulative ceilings, iterate over zip(widths, rates) directly (appending (float('inf'), rates[-1]) if rates has one extra catch-all rate). For marginal widths, track remaining = income and on each (width, rate) pair tax slice_amt = min(remaining, width), subtract remaining -= slice_amt, and stop once remaining <= 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 index tier_idx pointing to the first unfinished tier. When a positive payout delta arrives, advance from cumulative_income toward cumulative_income + delta, taxing each slice against brackets[tier_idx] and incrementing tier_idx only when cumulative_income hits that tier's ceiling. Because tier_idx only moves rightward across k tiers, handling m payouts takes O(m + k) total work instead of re-scanning all k tiers 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.2 evaluates to 0.30000000000000004). In accounting code, either represent earnings and rates with Python's decimal.Decimal constructed from strings (Decimal("0.12")), or work purely in exact integers using integer cents ($1 = 100 cents) and basis points (units where 1 basis point is 0.01%, or 1 / 10,000). Accumulate slice_cents * rate_bps in exact integer arithmetic across all tiers and divide by 10,000 once at the end under a specified rounding policy such as ROUND_HALF_UP.

Follow-up questions

Similar questions

More Interactive Brokers interview questions

All 3 Interactive Brokers questions →