Calculate Tax Under Progressive Income Brackets
Interactive BrokersSoftware Engineer · Online AssessmentLast updated
This problem tests the ability to iterate through sorted intervals and calculate values based on overlapping ranges, requiring careful boundary handling.
Problem Statement
Given an individual's total income and a list of tax brackets, calculate the total income tax owed. Tax brackets are progressive: you only pay the specific tax rate on the portion of income that falls within that specific bracket range.
A tax bracket is defined by an upper limit and a rate. The first bracket starts at 0. Any income exceeding the upper limit of the final bracket is taxed at the rate of that final bracket (or alternatively, assume the final bracket's limit is infinity).
Function Signature
def calculate_tax(income: float, brackets: list[tuple[float, float]]) -> float:
# brackets is a list of (upper_limit, rate)
# Example: [(10000, 0.1), (30000, 0.2), (float('inf'), 0.3)]
Constraints
income>= 0bracketsis sorted byupper_limitin ascending order.- Rates are between 0.0 and 1.0.
Examples
Example 1:
- Input:
income = 25000,brackets = [(10000, 0.1), (30000, 0.2)] - Calculation: First 10,000 taxed at 10% (1,000). Remaining 15,000 taxed at 20% (3,000).
- Output:
4000.0
Example 2:
- Input:
income = 5000,brackets = [(10000, 0.1)] - Calculation: 5,000 taxed at 10%.
- Output:
500.0
Edge Cases
- Income is 0.
- Income exceeds all provided bracket limits.
- Brackets list is empty or contains a single bracket.
Hints
Hint 1
Track the 'previous_limit' (starting at 0) as you iterate through the sorted brackets.
Hint 2
For each bracket, determine the 'taxable_amount' by taking the minimum of the current income and the bracket's upper limit, then subtracting the previous limit.
Hint 3
Ensure you stop the calculation or break the loop once your current income is fully accounted for.
Follow-up questions
- How would you modify your solution if the tax brackets were provided as a list of 'marginal income ranges' (e.g., [10000, 20000, 50000]) and a separate list of corresponding rates?
- What changes are needed if the income is provided as a stream of integers (e.g., daily earnings) rather than a single lump sum?
- How would you handle floating-point precision issues if the output requires a high degree of decimal accuracy?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.