Hourly Window Billing With Rate Overrides
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Compute the total usage bill across a half-open time window [start_time, end_time), where start_time is included and end_time is excluded. By default, every hour in the window costs base_rate.
You are also given overrides, a collection of mutually non-overlapping rate adjustments. Each entry [override_start, override_end, override_rate] defines a half-open window [override_start, override_end) priced at override_rate per hour. Whenever an adjustment window shares hours with [start_time, end_time), those shared hours are billed at override_rate instead of base_rate (even when override_rate is smaller than base_rate or 0). Any portion of an adjustment falling outside [start_time, end_time) is ignored.
Implement:
def calculate_total_charge(start_time: int, end_time: int, base_rate: int, overrides: List[List[int]]) -> int:
Return the total integer bill for [start_time, end_time).
Examples
Example 1
Input: start_time = 2, end_time = 14, base_rate = 8, overrides = [[5, 9, 15]]
Output: 124
The window [2, 14) spans 12 hours in total. The adjustment [5, 9) sits entirely inside [2, 14) and covers 4 hours at 15 per hour (4 * 15 = 60). The remaining 12 - 4 = 8 hours ([2, 5) and [9, 14)) use base_rate = 8 (8 * 8 = 64), giving 64 + 60 = 124.
Example 2
Input: start_time = 4, end_time = 12, base_rate = 6, overrides = [[1, 6, 10], [9, 15, 3]]
Output: 47
Clipping [1, 6) to [4, 12) yields [4, 6) (2 hours at 10 = 20), and clipping [9, 15) to [4, 12) yields [9, 12) (3 hours at 3 = 9). That leaves (12 - 4) - (2 + 3) = 3 hours ([6, 9)) at base_rate = 6 (3 * 6 = 18), for a total of 20 + 9 + 18 = 47.
Constraints
start_timeandend_timeare integers withstart_time < end_time(coordinates may be negative or as large as10^12).base_rate >= 0is an integer.0 <= len(overrides) <= 10^5, and each entry[override_start, override_end, override_rate]has integersoverride_start < override_endandoverride_rate >= 0.- Entries in
overridesnever overlap one another, may appear in any order, and may lie partially or completely outside[start_time, end_time).
Step-by-step walkthrough
Understand half-open intervals and the billing rules
We need to compute the total usage bill across a window
[start_time, end_time). Both the billing window and every rate adjustment use half-open interval notation[start, end), meaningstartis included andendis excluded:[4, 12)covers the 8 individual one-hour slots4, 5, 6, 7, 8, 9, 10, 11, so its duration is12 - 4 = 8hours.[5, 9)covers hours5, 6, 7, 8(9 - 5 = 4hours).- Two intervals that merely touch at a boundary, such as
[4, 12)and[12, 16), share zero hours because hour12is excluded from[4, 12).
Example 2: Window [4, 12) at 6/hr, Overrides [1, 6) at 10/hr and [9, 15) at 3/hr Hours: 1 2 3 | 4 5 6 7 8 9 10 11 | 12 13 14 Window: [=====|--------- 6/hr -|========] Overrides: [=== 10/hr ===) [==== 3/hr =========) ^-------^ ^---^ ^------^ ^--------^ ignored 2 hrs 3 hrs ignoredTwo guarantees keep our computation clean:
- Only the slice of an override that sits inside
[start_time, end_time)affects the bill. - Entries in
overridesnever overlap one another, so every hour in the window is governed by at most one override (and otherwise falls back tobase_rate).
Why billing hour by hour is too slow
A straightforward first attempt loops
for hour in range(start_time, end_time):and checks whether any override covers that hour. That logic is right (and makes an ideal brute-force cross-check on tiny coordinates), but its speed scales with the durationend_time - start_timerather than with how many overrides exist.If a billing window stretches from
0to1,000,000,000,000with a single override, an hour-by-hour loop executes a trillion iterations and never finishes. Instead, we can compute each override's shared duration directly from its two endpoints inO(1)arithmetic.Intersection of two half-open intervals
When does an hour
tbelong to both[start_a, end_a)and[start_b, end_b)?tmust be at leaststart_aand at leaststart_b->t >= max(start_a, start_b).tmust be strictly belowend_aand strictly belowend_b->t < min(end_a, end_b).
Thus the overlap of any two half-open intervals is
[overlap_start, overlap_end)whereoverlap_start = max(start_a, start_b)andoverlap_end = min(end_a, end_b):Window [4, 12): 4=============================12 1) Left overhang [1, 6): 1========6 max(4,1)=4, min(12,6)=6 -> 2 hrs 2) Inside [5, 9): 5=========9 max(4,5)=5, min(12,9)=9 -> 4 hrs 3) Touching [12, 16): 12===16 max(4,12)=12, min(12,16)=12 -> 0 hrs 4) Disjoint [14, 18): 14==18 max(4,14)=14, min(12,18)=12 -> 12 <= 14 -> 0 hrsNotice Case 4: whenever two intervals miss each other completely,
overlap_endends up smaller thanoverlap_start(12 < 14). Checkingif overlap_end > overlap_start:handles enclosed, overhanging, touching, and completely separate intervals in one clean formula without ever producing negative durations.from typing import Any, Dict, List, Optional, Set, Tuple def overlap_length(start_a: int, end_a: int, start_b: int, end_b: int) -> int: """Return the number of shared hours between half-open intervals [start_a, end_a) and [start_b, end_b).""" # Two intervals overlap only after BOTH have started and before EITHER has ended. overlap_start = max(start_a, start_b) overlap_end = min(end_a, end_b) # Strict '>' because intervals are half-open: touching at one point (e.g. [0, 5) and [5, 8)) shares 0 hours. if overlap_end > overlap_start: return overlap_end - overlap_start return 0Combine overridden hours and base-rate hours
Now scan
overridesonce while maintaining two running totals:covered_hours: total hours inside[start_time, end_time)claimed by overrides.override_cost: total dollar amount contributed by those overridden hours (hours_in_period * override_rate).
Because input overrides never overlap one another, their intersections with
[start_time, end_time)never overlap one another either — no hour is ever double-counted, andoverridesdoes not even need to be sorted! Every remaining hour in[start_time, end_time)((end_time - start_time) - covered_hours) is billed atbase_rate.def calculate_total_charge(start_time: int, end_time: int, base_rate: int, overrides: List[List[int]]) -> int: # Phase 1: Sum the hours and cost covered by overrides inside [start_time, end_time). # covered_hours: total integer hours inside the billing period governed by an override. # override_cost: total dollar charge contributed by those overridden hours. covered_hours = 0 override_cost = 0 # Each element in overrides has shape [override_start, override_end, override_rate] (list or tuple). for override in overrides: override_start, override_end, override_rate = override hours_in_period = overlap_length(start_time, end_time, override_start, override_end) covered_hours += hours_in_period override_cost += hours_in_period * override_rate # Phase 2: Bill all remaining hours of the billing period at base_rate. # Because overrides never overlap each other, their clipped pieces never double-count any hour. total_period_hours = end_time - start_time base_hours = total_period_hours - covered_hours base_cost = base_hours * base_rate return base_cost + override_costTrace both examples step by step
Example 1:
calculate_total_charge(2, 14, 8, [[5, 9, 15]])Override [5, 9, 15] vs window [2, 14): overlap_start = max(2, 5) = 5 overlap_end = min(14, 9) = 9 hours_in_period = 9 - 5 = 4 hours covered_hours = 4, override_cost = 4 * 15 = 60 Remaining base hours: base_hours = (14 - 2) - 4 = 8 hours base_cost = 8 * 8 = 64 total = 64 + 60 = 124Example 2:
calculate_total_charge(4, 12, 6, [[1, 6, 10], [9, 15, 3]])Override 1 — [1, 6, 10] vs window [4, 12): overlap_start = max(4, 1) = 4, overlap_end = min(12, 6) = 6 hours_in_period = 6 - 4 = 2 hours -> cost += 2 * 10 = 20 Override 2 — [9, 15, 3] vs window [4, 12): overlap_start = max(4, 9) = 9, overlap_end = min(12, 15) = 12 hours_in_period = 12 - 9 = 3 hours -> cost += 3 * 3 = 9 Totals: covered_hours = 2 + 3 = 5, override_cost = 20 + 9 = 29 base_hours = (12 - 4) - 5 = 3, base_cost = 3 * 6 = 18 total = 18 + 29 = 47Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def overlap_length(start_a: int, end_a: int, start_b: int, end_b: int) -> int: """Return the number of shared hours between half-open intervals [start_a, end_a) and [start_b, end_b).""" # Two intervals overlap only after BOTH have started and before EITHER has ended. overlap_start = max(start_a, start_b) overlap_end = min(end_a, end_b) # Strict '>' because intervals are half-open: touching at one point (e.g. [0, 5) and [5, 8)) shares 0 hours. if overlap_end > overlap_start: return overlap_end - overlap_start return 0 def calculate_total_charge(start_time: int, end_time: int, base_rate: int, overrides: List[List[int]]) -> int: # Phase 1: Sum the hours and cost covered by overrides inside [start_time, end_time). # covered_hours: total integer hours inside the billing period governed by an override. # override_cost: total dollar charge contributed by those overridden hours. covered_hours = 0 override_cost = 0 # Each element in overrides has shape [override_start, override_end, override_rate] (list or tuple). for override in overrides: override_start, override_end, override_rate = override hours_in_period = overlap_length(start_time, end_time, override_start, override_end) covered_hours += hours_in_period override_cost += hours_in_period * override_rate # Phase 2: Bill all remaining hours of the billing period at base_rate. # Because overrides never overlap each other, their clipped pieces never double-count any hour. total_period_hours = end_time - start_time base_hours = total_period_hours - covered_hours base_cost = base_hours * base_rate return base_cost + override_cost✅ Submit now — all tests should pass.
Intuition & how it works
Picture painting an 8-foot section of fence [4, 12) where standard paint costs $6 per foot (base_rate), except for non-overlapping specialty sections (overrides). Whenever a specialty order extends past your fence posts, you saw off the overhang at posts 4 and 12, pay the specialty rate for the feet that actually sit on your fence, and paint the remaining 8 - covered_feet feet at the standard rate.
Simulating the invoice one hour at a time fails whenever the window is wide — a range from 0 to 10^12 would iterate a trillion times even when overrides contains a single entry. Sorting the overrides to measure gaps between neighbors works, but adds O(k log k) sorting overhead and extra boundary tracking that we do not need when overrides are already disjoint.
Instead, we model every window [start, end) as a half-open interval — a range that includes start and excludes end, so its length is end - start — and intersect each override directly with [start_time, end_time) via [max(start_time, override_start), min(end_time, override_end)). Because input overrides never overlap one another, their intersections never overlap either, allowing us to sum covered hours in a single pass.
On Example 2 (start_time = 4, end_time = 12, base_rate = 6, overrides [1, 6, 10] and [9, 15, 3]):
- Intersect
[1, 6)with[4, 12)->[4, 6), giving2hours costing2 * 10 = 20. - Intersect
[9, 15)with[4, 12)->[9, 12), giving3hours costing3 * 3 = 9. - Subtract
2 + 3 = 5covered hours from the12 - 4 = 8window hours, leaving3base hours costing3 * 6 = 18, for a total of20 + 9 + 18 = 47.
Complexity
Let k be the number of entries in overrides.
- Time:
O(k). We iterate through thekoverrides once and performO(1)arithmetic (max,min, subtraction, multiplication) per entry, completely independent of the spanend_time - start_time. - Space:
O(1). Only four scalar accumulators (covered_hours,override_cost,base_hours,base_cost) are kept in memory regardless of input size.
Edge cases
- Empty
overrideslist:covered_hoursremains0, so the full(end_time - start_time)span is charged atbase_rate. - An override enclosing the entire window (e.g.
[-5, 20, 3]on[0, 10)): Intersected length equalsend_time - start_time,base_hoursbecomes0, and every hour usesoverride_rate. - Overrides touching a boundary (e.g.
[0, 4, 99]or[12, 16, 99]against[4, 12)):overlap_end == overlap_start, sooverlap_end > overlap_startisFalseand0hours are charged. - Overrides completely outside the window:
overlap_end < overlap_start, which clamps cleanly to0instead of a negative duration. - Discount or zero-price overrides (
override_rate < base_rateoroverride_rate == 0): Covered hours still count towardcovered_hours, preventing them from being chargedbase_ratea second time. - Unsorted overrides or negative timestamps: Each entry is intersected independently via comparisons and subtraction, so unsorted inputs and negative integers work identically.
- Huge spans (e.g.
10^12hours): Python integers have arbitrary precision; in fixed-width languages such as C++ or Java, use 64-bit integers (long long/long) sohours * ratecannot overflow.
Common mistakes
- Billing unclipped override durations. Using
override_end - override_startcharges hours outside[start_time, end_time)atoverride_rateand subtracts too many hours frombase_hours(turning Example 2 into19instead of47). - Off-by-one from closed-interval arithmetic (
end - start + 1).[5, 9)covers hours5, 6, 7, 8(4hours, not5), and closed-interval math falsely charges1hour when two intervals merely touch at an endpoint. - Forgetting to clamp non-overlapping intervals to
0. Withoutif overlap_end > overlap_start, an outside override like[14, 18)against[4, 12)produces12 - 14 = -2hours, corrupting bothcovered_hoursandoverride_cost. - Stepping hour by hour. Looping over
range(start_time, end_time)times out as soon as coordinates span millions or billions of hours.
Follow-up questions
- How would your algorithm change if override windows could overlap one another and the most expensive active rate always won? Independent clipping would double-count shared hours, so switch to a sweep-line algorithm — a technique that cuts the timeline at every interval start and end coordinate and processes elementary slices from left to right. Keep a max-heap (a priority queue that exposes the largest active rate in
O(1)time and updates inO(log k)time) of overrides whosestart <= slice_start; before pricing each elementary slice[a, b), pop expired heap entries withend <= a, then charge(b - a)hours at the top heap rate (orbase_rateonly when the heap is empty, since an active discount override still supersedesbase_rate). Sorting theO(k)cut points dominates atO(k log k)time.
```python import heapq
def charge_highest_override_wins(start_time, end_time, base_rate, overrides): clipped = [] cut_points = {start_time, end_time} for o_start, o_end, rate in overrides: s, e = max(start_time, o_start), min(end_time, o_end) if s < e: clipped.append((s, e, rate)) cut_points.add(s) cut_points.add(e) clipped.sort() sorted_points = sorted(cut_points)
max_heap = [] # (-rate, end) of active overrides
idx = 0
total = 0
for j in range(len(sorted_points) - 1):
a, b = sorted_points[j], sorted_points[j + 1]
while idx < len(clipped) and clipped[idx][0] <= a:
heapq.heappush(max_heap, (-clipped[idx][2], clipped[idx][1]))
idx += 1
while max_heap and max_heap[0][1] <= a:
heapq.heappop(max_heap)
active_rate = -max_heap[0][0] if max_heap else base_rate
total += active_rate * (b - a)
return total
```
- Suppose a fixed catalog of millions of disjoint overrides is queried repeatedly over huge time spans—how can each query run faster than O(k)? Sort the
kdisjoint overrides once inO(k log k)time and precompute two prefix sum arrays — running-total arrays that return the sum across any contiguous index slice[i..j]inO(1)time — one for override durations and one for override charges. Each query[start_time, end_time)then runs binary search inO(log k)time to locate the first override withoverride_end > start_timeand the last override withoverride_start < end_time, manually clips at most those two boundary overrides, and looks up all strictly interior overrides inO(1)via the prefix sums forO(log k)total query time. If overrides are also inserted and removed dynamically, maintain them in a balanced search tree augmented with subtree duration/cost sums (or a Fenwick tree, an array-backed tree supporting point updates and prefix sums inO(log k)time). - What numerical pitfalls arise if timestamps are given as IEEE-754 floats, and how should a production billing engine represent them? Binary IEEE-754 floats cannot represent base-10 fractions such as
0.1or0.01exactly (0.1 + 0.2 != 0.3), leading to cumulative rounding drift in invoice totals and inconsistent</<=boundary checks when two intervals meet at a fractional timestamp. Production billing engines normalize timestamps at ingestion into integer ticks of an atomic unit (such as milliseconds, microseconds, or integer seconds) and store money in integer minor units (such as cents or micro-dollars) so every intersection and multiplication stays exact. When arbitrary decimal inputs must be accepted directly, compute withdecimal.Decimal(or rationalfractions.Fraction) and apply an explicit banker's rounding rule (ROUND_HALF_EVEN) once at invoice finalization.
Follow-up questions
- How would your algorithm change if override windows could overlap one another and the most expensive active rate always won?
- Suppose a fixed catalog of millions of disjoint overrides is queried repeatedly over huge time spans—how can each query run faster than O(k)?
- What numerical pitfalls arise if timestamps are given as IEEE-754 floats, and how should a production billing engine represent them?
Similar questions
- Longest-Running Timeline Tags After Overwrites
- Design a Real-Time Workspace Chat Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance