#2303

Calculate Amount Paid in Taxes

Easy
ArraySimulationArraySimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

This approach efficiently calculates the tax by iterating through the brackets just once, using a single loop. We keep track of the previous upper limit and only calculate the taxable income for the relevant brackets.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable 'tax' to 0 and 'prev' to 0.
  2. 2Step 2: Loop through each bracket, calculating the taxable income based on the current income and the previous upper limit.
  3. 3Step 3: If the income exceeds the current bracket's upper limit, calculate the tax for that segment and update 'prev'.
  4. 4Step 4: If the income is less than the current bracket's upper limit, calculate the tax for the remaining income and break the loop.
solution.py11 lines
1def calculateTax(brackets, income):
2    tax = 0
3    prev = 0
4    for upper, percent in brackets:
5        if income > prev:
6            taxable_income = min(income, upper) - prev
7            tax += taxable_income * (percent / 100)
8            prev = upper
9        else:
10            break
11    return tax

Complexity note: The complexity is O(n) because we only loop through the brackets once, making it efficient for larger inputs.

  • 1Understanding how tax brackets work is crucial for calculating taxes accurately.
  • 2The order of brackets matters; they must be processed sequentially.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.