Calculate Amount Paid in Taxes solution and explanation
4 more videos on this problem
2303. Calculate Amount Paid in Taxes (Leetcode Easy)Programming Live with Larry · 7:06 · 791 views
Leetcode 2303. Calculate Amount Paid in Taxes | HindiThinkCode · 3:24 · 703 views
Leetcode Weekly contest 297 Easy- Calculate Amount Paid in TaxesPrakhar Agrawal · 5:28 · 413 views
LeetCode 2303 | Calculate Amount Paid in Taxes | Array | JavaSleepy Cracker · 5:05 · 249 views
Calculate Amount Paid in Taxes - LeetCode 2303 - Javaalgobest - Computer Science · 8:12 · 142 views
The problem
You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).
Tax is calculated as follows:
- The first
upper0dollars earned are taxed at a rate ofpercent0. - The next
upper1 - upper0dollars earned are taxed at a rate ofpercent1. - The next
upper2 - upper1dollars earned are taxed at a rate ofpercent2. - And so on.
You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: brackets = [[3,50],[7,10],[12,25]], income = 10 Output: 2.65000 Explanation: Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket. The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively. In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.
Example 2:
Input: brackets = [[1,0],[4,25],[5,50]], income = 2 Output: 0.25000 Explanation: Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket. The tax rate for the two tax brackets is 0% and 25%, respectively. In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.
Example 3:
Input: brackets = [[2,50]], income = 0 Output: 0.00000 Explanation: You have no income to tax, so you have to pay a total of $0 in taxes.
Constraints:
1 <= brackets.length <= 1001 <= upperi <= 10000 <= percenti <= 1000 <= income <= 1000upperiis sorted in ascending order.- All the values of
upperiare unique. - The upper bound of the last tax bracket is greater than or equal to
income.
Approach overview
Problem Overview: You are given progressive tax brackets where each bracket defines an upper income limit and the percentage tax applied to that portion of income. The task is to compute the total tax paid for a given income by applying each bracket sequentially until the income limit is reached.
Approach 1: Iterative Calculation of Taxes by Bracket (O(n) time, O(1) space)
This approach directly simulates how progressive taxes are calculated in real systems. Iterate through the brackets array and determine how much of your income falls inside the current bracket. For each bracket, compute the taxable portion as min(income, upperLimit) - previousLimit, multiply it by the tax percentage, and accumulate the result. Update the previous limit as you move to the next bracket. Once the income falls below the current bracket's upper limit, the remaining tax can be computed and the loop stops. This method uses only simple arithmetic and a single pass through the array, making it ideal for problems involving array traversal and direct simulation.
Approach 2: Cumulative Summation with Early Exit (O(n) time, O(1) space)
This variation also processes brackets sequentially but focuses on accumulating the taxable income incrementally. Instead of recalculating limits repeatedly, track the remaining income and process each bracket's capacity. For each bracket, determine how much income can be taxed inside that range and add the computed tax to a running total. If the remaining income becomes zero or negative, break early since no further brackets apply. The early exit avoids unnecessary iterations when income lies within lower brackets. The algorithm still runs in linear time relative to the number of brackets and requires constant extra memory.
Recommended for interviews: The iterative bracket simulation is the expected solution. Interviewers want to see that you correctly model progressive tax calculation and handle bracket boundaries without off‑by‑one mistakes. Both implementations run in O(n) time with O(1) space, but the direct bracket iteration clearly demonstrates your understanding of range processing and controlled iteration over arrays.
Approach 1: Iterative Calculation of Taxes by Bracket
This approach involves iterating through each tax bracket and calculating the tax for each, based on the remaining income. We begin taxing from the first dollar and proceed until all income is subject to tax based on the relevant brackets.
def calculateTax(brackets, income):
total_tax = 0.0
previous_upper = 0
for upper, percent in brackets:
if income <= 0:
break
taxable_income = min(income, upper - previous_upper)
total_tax += taxable_income * percent / 100.0
income -= taxable_income
previous_upper = upper
return total_taxpublic class TaxCalculator {
public static double calculateTax(int[][] brackets, int income) {
double totalTax = 0.0;
int previousUpper = 0;
for (int[] bracket : brackets) {
if (income <= 0) break;
int upper = bracket[0], percent = bracket[1];
int taxableIncome = Math.min(income, upper - previousUpper);
totalTax += taxableIncome * percent / 100.0;
income -= taxableIncome;
previousUpper = upper;
}
return totalTax;
}
}#include <vector>
#include <algorithm>
using namespace std;
double calculateTax(vector<vector<int>>& brackets, int income) {
double total_tax = 0.0;
int previous_upper = 0;
for (const auto& bracket : brackets) {
if (income <= 0)
break;
int upper = bracket[0], percent = bracket[1];
int taxable_income = min(income, upper - previous_upper);
total_tax += taxable_income * percent / 100.0;
income -= taxable_income;
previous_upper = upper;
}
return total_tax;
}function calculateTax(brackets, income) {
let totalTax = 0.0;
let previousUpper = 0;
for (let i = 0; i < brackets.length; i++) {
if (income <= 0) break;
const [upper, percent] = brackets[i];
const taxableIncome = Math.min(income, upper - previousUpper);
totalTax += taxableIncome * percent / 100.0;
income -= taxableIncome;
previousUpper = upper;
}
return totalTax;
}public class Solution {
public double CalculateTax(int[][] brackets, int income) {
double totalTax = 0.0;
int previousUpper = 0;
foreach (var bracket in brackets) {
if (income <= 0) break;
int upper = bracket[0];
int percent = bracket[1];
int taxableIncome = Math.Min(income, upper - previousUpper);
totalTax += taxableIncome * percent / 100.0;
income -= taxableIncome;
previousUpper = upper;
}
return totalTax;
}
}In Python, the function calculateTax iteratively computes the tax by subtracting from the income the amount taxed at each bracket. The variable previous_upper tracks the upper boundary of the last considered bracket to determine the current bracket size.
Time Complexity: O(n), where n is the number of tax brackets.
Space Complexity: O(1), since only a few auxiliary variables are used.
Approach 2: Cumulative Summation with Early Exit
This approach involves iterating through each bracket while cumulatively summing the taxes, and exiting early if the full income has been taxed. It uses a cumulative difference strategy where each bracket contributes only the difference from the previous bracket.
def calculateTax(brackets, income):
total_tax = 0.0
prev_upper = 0
for upper, percent in brackets:
if income <= 0:
break
if income > prev_upper:
taxable_income = min(upper, income) - prev_upper
total_tax += taxable_income * percent / 100.0
prev_upper = upper
return total_taxpublic class TaxCalculator {
public static double calculateTax(int[][] brackets, int income) {
double totalTax = 0.0;
int prevUpper = 0;
for (int[] bracket : brackets) {
if (income <= 0) break;
if (income > prevUpper) {
int taxableAmount = Math.min(income, bracket[0]) - prevUpper;
totalTax += taxableAmount * bracket[1] / 100.0;
prevUpper = bracket[0];
}
}
return totalTax;
}
}#include <vector>
using namespace std;
double calculateTax(vector<vector<int>>& brackets, int income) {
double total_tax = 0.0;
int prev_upper = 0;
for (auto& bracket : brackets) {
if (income <= 0) break;
if (income > prev_upper) {
int taxable_amount = min(income, bracket[0]) - prev_upper;
total_tax += taxable_amount * bracket[1] / 100.0;
prev_upper = bracket[0];
}
}
return total_tax;
}function calculateTax(brackets, income) {
let totalTax = 0.0;
let prevUpper = 0;
for (let i = 0; i < brackets.length; i++) {
if (income <= prevUpper) break;
const taxableIncome = Math.min(income, brackets[i][0]) - prevUpper;
totalTax += taxableIncome * brackets[i][1] / 100.0;
prevUpper = brackets[i][0];
}
return totalTax;
}public class Solution {
public double CalculateTax(int[][] brackets, int income) {
double totalTax = 0.0;
int prevUpper = 0;
foreach (var bracket in brackets) {
if (income <= prevUpper) break;
int taxableIncome = Math.Min(income, bracket[0]) - prevUpper;
totalTax += taxableIncome * bracket[1] / 100.0;
prevUpper = bracket[0];
}
return totalTax;
}
}In this Python solution, the algorithm checks if there's any income left to tax before continuing with processing a new bracket. It ensures minimal computation by bounding taxable income calculation by using min on upper and income.
Time Complexity: O(n), with n being the number of brackets.
Space Complexity: O(1), as no additional space proportionate to input size is required.
Approach 3: Simulation
We traverse brackets, and for each tax bracket, we calculate the tax amount for that bracket, then accumulate it.
The time complexity is O(n), where n is the length of brackets. The space complexity is O(1).
function calculateTax(brackets: number[][], income: number): number {
let ans = 0;
let prev = 0;
for (const [upper, percent] of brackets) {
ans += Math.max(0, Math.min(income, upper) - prev) * percent;
prev = upper;
}
return ans / 100;
}func calculateTax(brackets [][]int, income int) float64 {
var ans, prev int
for _, e := range brackets {
upper, percent := e[0], e[1]
ans += max(0, min(income, upper)-prev) * percent
prev = upper
}
return float64(ans) / 100.0
}impl Solution {
pub fn calculate_tax(brackets: Vec<Vec<i32>>, income: i32) -> f64 {
let mut res = 0f64;
let mut pre = 0i32;
for bracket in brackets.iter() {
res += f64::from(income.min(bracket[0]) - pre) * f64::from(bracket[1]) * 0.01;
if income <= bracket[0] {
break;
}
pre = bracket[0];
}
res
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterative Calculation of Taxes by Bracket | Time Complexity: O(n), where n is the number of tax brackets. |
| Cumulative Summation with Early Exit | Time Complexity: O(n), with n being the number of brackets. |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Calculation of Taxes by Bracket | O(n) | O(1) | Standard solution when simulating progressive tax brackets |
| Cumulative Summation with Early Exit | O(n) | O(1) | Useful when income often falls in lower brackets and early termination saves iterations |
Frequently asked questions
Is Calculate Amount Paid in Taxes easy or hard?
Calculate Amount Paid in Taxes is classified as an Easy problem. The challenge mainly involves correctly handling bracket boundaries and applying the tax percentage to the correct portion of income using simple array iteration.
Calculate Amount Paid in Taxes Python/Java solution
The solution in Python or Java follows the same logic: iterate through each bracket, compute the taxable portion of income within that range, multiply by the tax percentage, and accumulate the total. Both implementations run in O(n) time with constant extra space.
How to solve Calculate Amount Paid in Taxes in O(n)?
Traverse the brackets sequentially and determine how much of the income lies inside each bracket range. Compute the taxable portion using the difference between the current upper limit and the previous limit. Multiply that portion by the tax rate and accumulate the result until the income is fully processed.
What is the best approach for Calculate Amount Paid in Taxes?
The best approach is iterating through the tax brackets and computing the taxable portion for each range. For every bracket, calculate the income portion within that range and multiply it by the given tax percentage. This simulation runs in O(n) time and O(1) space, where n is the number of brackets.
Is Calculate Amount Paid in Taxes asked at Google/Amazon/Meta?
Problems involving progressive ranges and simulation frequently appear in coding interviews at large tech companies. While this exact problem is common on LeetCode, similar array simulation questions are used by companies like Amazon and Google to test basic algorithmic reasoning.
What data structure is used in Calculate Amount Paid in Taxes?
The primary data structure is an array that stores tax brackets as pairs of values: upper income limit and tax percentage. The algorithm iterates through the array sequentially and performs arithmetic calculations for each bracket.
What is the time complexity of Calculate Amount Paid in Taxes?
The time complexity is O(n) because the algorithm processes each tax bracket once. Space complexity is O(1) since only a few variables are used to track the previous limit, current taxable income, and accumulated tax.
