KatInterview

Tiered Subscription Invoice with Mid-Cycle Proration

Arrays & HashingAuto-graded · 19 test cases
HardAuto-gradedArrays & Hashingsimulationmathaggregation

Last updated

Tests ability to combine prorated flat fees with two-tier volume pricing over a half-open time window.

Problem

You are writing the core calculation for a subscription billing engine. Given a list of usage records and a plan configuration, compute the total amount owed for a billing cycle.

The invoice has two independent components:

1. Flat Subscription Fee (Prorated)

Every subscriber owes a flat base_price for the cycle. If the subscriber enrolled after the cycle started, the flat fee is scaled down proportionally:

prorated_base = base_price × (end_time − enrollment_time) / (end_time − start_time)

A subscriber enrolled exactly at start_time owes the full fee. One enrolled exactly at end_time owes nothing.

2. Volume-Based Usage Charge (Not Prorated)

Count the total units across all usage records whose timestamp falls inside the half-open window [start_time, end_time). Records at exactly end_time belong to the next cycle and must be excluded.

Apply two-tier pricing to the cycle total:

Units consumedRate per unit
First 100 units$0.50
Every unit beyond 100$0.25

Usage charges are never prorated, regardless of enrollment time.

Final Invoice

invoice = prorated_base + usage_charge

Return the result as a float.


Constraints

  • 1 ≤ end_time − start_time (the billing window always has positive length)
  • start_time ≤ enrollment_time ≤ end_time
  • All timestamps are non-negative integers
  • quantity values are non-negative integers
  • Usage records are not guaranteed to be in timestamp order
  • base_price is a non-negative float
  • Records outside [start_time, end_time) must be ignored

Examples

Example 1

Input: compute_invoice([{'timestamp': 100, 'quantity': 60}, {'timestamp': 200, 'quantity': 60}], {'base_price': 100}, 0, 400, 200)

Output: 105

Example 2

Input: compute_invoice([], {'base_price': 75}, 0, 300, 0)

Output: 75

Example 3

Input: compute_invoice([{'timestamp': 10, 'quantity': 100}], {'base_price': 50}, 0, 100, 0)

Output: 100

Hints

Hint 1

Start by computing the two components — flat fee and usage charge — completely independently, then add them at the end. Mixing them together will cause confusion.

Hint 2

For the tiered usage charge, you only need one number: the total units in the window. Once you have it, `min(total, 100)` gives tier-1 units and `max(0, total - 100)` gives tier-2 units.

Hint 3

The records are unsorted, but order does not matter here — you're computing a single cycle total, not tracking state over time. A single linear pass to filter and sum is all you need.