KatInterview

Metered Usage Bill with Special Rate Windows

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalsintervalssweepmath

Last updated

Compute a total bill over a half-open time window where disjoint special-rate windows replace the default hourly rate, testing interval clipping and boundary handling.

A service is billed by the hour. Over a billing window you must work out the total amount owed, given a default hourly price and a set of special-rate windows that replace the default price while they are active.

Task

Write a function that takes:

  • window_start and window_end: the billing window. Treat it as half-open, [window_start, window_end), so the start hour is counted and the end hour is not.
  • default_rate: the price per hour used whenever no special window applies.
  • special_windows: a list of [s, e, r] triples. Each triple describes a half-open window [s, e) during which the price per hour is r instead of default_rate.

Return the total charge for the billing window as an integer.

Rules

  • Every hour in [window_start, window_end) is charged exactly once.
  • An hour covered by a special window is charged at that window's rate r. Any other hour is charged at default_rate.
  • Special windows may extend beyond the billing window, in either direction, or lie entirely outside it. Only the part inside the billing window counts.
  • Special windows that merely touch the billing window at a single boundary point contribute nothing, because the intervals are half-open.
  • A special window with s >= e is empty and contributes nothing.
  • A special rate may be lower than, equal to, or higher than the default rate, and may be zero.
  • If special_windows is empty, the answer is (window_end - window_start) * default_rate.

Constraints

  • All times are integers and window_start < window_end.
  • Special windows do not overlap one another.
  • Rates are integers.
  • The list of special windows may be empty.
  • The windows may be given in any order.

Examples

Example 1

Input: compute_bill(0, 10, 10, [[2, 5, 20]])

Output: 130

Example 2

Input: compute_bill(0, 10, 5, [[8, 12, 2]])

Output: 44

Hints

Hint 1

Start by pretending the whole billing window is charged at the default rate. What would the total be?

Hint 2

For each special window, find the part that lies inside the billing window using max of the starts and min of the ends. Ignore it if that part is empty.

Hint 3

For the hours inside the clipped part, the charge changes by (special rate - default rate) per hour. Because special windows never overlap, you can add these corrections independently, and negative corrections need no special case.