Skip to main content

Search

Search problems, hooks, and pages

Calculate Electricity Bill

Given a number of consumed units, calculate the total electricity bill using tiered (slab-based) pricing. Each slab covers a band of units at a fixed per-unit rate, and any units beyond the last fixed slab are charged at the top rate. This is a classic "slab/bracket" problem (the same shape as income-tax calculation) that tests whether you can turn a rule table into clean, maintainable code.

Examples

Input: units = 230
Output: ₹1500
// 100×₹5 (500) + 100×₹7 (700) + 30×₹10 (300) = ₹1500.
Input: units = 120
Output: ₹640
// 100×₹5 (500) + 20×₹7 (140) = ₹640.
Input: units = 90
Output: ₹450
// All 90 units fall in the first slab: 90×₹5.
Input: units = 0
Output: ₹0

Constraints

  • Slabs: 0–100 → ₹5/unit, 101–200 → ₹7/unit, 201–300 → ₹10/unit, above 300 → ₹12/unit.
  • Each slab rate applies only to the units within that band (marginal pricing), not the whole bill.
  • units is a non-negative number; 0 units → ₹0.
mathslab-pricingarrayreducelogic

Important

Interview Tip

The trap is to charge the whole amount at one rate based on the total — the rates are MARGINAL, like tax brackets. Lead with the if/else version to show you understand the slabs, then refactor to the data-driven table and point out that a tariff change becomes a one-line data edit instead of a logic rewrite.

Approach: Brute Force

A hardcoded if / else-if chain, one branch per slab boundary. Easiest to read and explain, and a fine first answer — but every tariff change forces you to rewrite the branches and re-derive the cumulative constants.

Complexity

Time: O(1)Space: O(1)

Pros

  • Trivial to understand
  • No data structures needed
  • Obviously correct

Cons

  • Constants are duplicated and error-prone
  • Adding/changing a slab means editing logic
  • Does not generalise