Calculate Amount Paid in Taxes [Progressive Income tax]
XXX. Calculate Progressive Income Tax
Math
Array
Problem Statement:
Calculate the tax for a given income using tax brackets. Each bracket contains an upper limit and tax percentage.
- Brackets are sorted by upper limit
- Each bracket has different tax rate
- Tax is calculated progressively
Implementation:
Java Solution:
public double calculateTax(int[][] brackets, int income) {
double taxes = 0;
int i = 0, upper = 0; // Track previous bracket limit
while (income > 0 && i < brackets.length) {
int bracketRange = brackets[i][0] - upper; // Current bracket size
int taxableAmount = Math.min(income, bracketRange); // Amount to tax
upper = brackets[i][0]; // Update upper limit
taxes += (double) taxableAmount * brackets[i][1] / 100; // Add tax
income -= taxableAmount; // Reduce remaining income
i++;
}
return taxes;
}
Python Solution:
def calculateTax(self, brackets: List[List[int]], income: int) -> float:
taxes = 0
upper = 0
for amount, percent in brackets:
if income <= 0: break
bracket_range = amount - upper # Current bracket size
taxable = min(income, bracket_range) # Amount to tax
upper = amount # Update upper limit
taxes += taxable * percent / 100 # Add tax
income -= taxable # Reduce remaining income
return taxes
C++ Solution:
double calculateTax(vector>& brackets, int income) {
double taxes = 0;
int upper = 0;
for (const auto& bracket : brackets) {
if (income <= 0) break;
int bracketRange = bracket[0] - upper; // Current bracket size
int taxableAmount = min(income, bracketRange); // Amount to tax
upper = bracket[0]; // Update upper limit
taxes += (double)taxableAmount * bracket[1] / 100; // Add tax
income -= taxableAmount; // Reduce remaining income
}
return taxes;
}
Complexity:
Time Complexity: O(n), where n is number of brackets
Space Complexity: O(1), constant extra space
Explanation:
-
**Bracket Processing**:
- Track previous bracket's upper limit
- Calculate size of current bracket
- Find taxable amount in current bracket
-
**Tax Calculation**:
- Apply tax rate to taxable amount
- Add to running total of taxes
- Reduce remaining income
-
**Implementation Notes**:
- Handle type conversion for accurate calculation
- Early exit when no income remains
- Use double for tax amounts to handle decimals