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_time and end_time are integers with start_time < end_time (coordinates may be negative or as large as 10^12).
  • base_rate >= 0 is an integer.
  • 0 <= len(overrides) <= 10^5, and each entry [override_start, override_end, override_rate] has integers override_start < override_end and override_rate >= 0.
  • Entries in overrides never overlap one another, may appear in any order, and may lie partially or completely outside [start_time, end_time).

Step-by-step walkthrough

  1. 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), meaning start is included and end is excluded:

    • [4, 12) covers the 8 individual one-hour slots 4, 5, 6, 7, 8, 9, 10, 11, so its duration is 12 - 4 = 8 hours.
    • [5, 9) covers hours 5, 6, 7, 8 (9 - 5 = 4 hours).
    • Two intervals that merely touch at a boundary, such as [4, 12) and [12, 16), share zero hours because hour 12 is 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     ignored
    

    Two guarantees keep our computation clean:

    • Only the slice of an override that sits inside [start_time, end_time) affects the bill.
    • Entries in overrides never overlap one another, so every hour in the window is governed by at most one override (and otherwise falls back to base_rate).
  2. 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 duration end_time - start_time rather than with how many overrides exist.

    If a billing window stretches from 0 to 1,000,000,000,000 with 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 in O(1) arithmetic.

  3. Intersection of two half-open intervals

    When does an hour t belong to both [start_a, end_a) and [start_b, end_b)?

    • t must be at least start_a and at least start_b -> t >= max(start_a, start_b).
    • t must be strictly below end_a and strictly below end_b -> t < min(end_a, end_b).

    Thus the overlap of any two half-open intervals is [overlap_start, overlap_end) where overlap_start = max(start_a, start_b) and overlap_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 hrs
    

    Notice Case 4: whenever two intervals miss each other completely, overlap_end ends up smaller than overlap_start (12 < 14). Checking if 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 0
    
  4. Combine overridden hours and base-rate hours

    Now scan overrides once 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, and overrides does not even need to be sorted! Every remaining hour in [start_time, end_time) ((end_time - start_time) - covered_hours) is billed at base_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_cost
    
  5. Trace 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      = 124
    

    Example 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 = 47
    
  6. Complete 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]):

  1. Intersect [1, 6) with [4, 12) -> [4, 6), giving 2 hours costing 2 * 10 = 20.
  2. Intersect [9, 15) with [4, 12) -> [9, 12), giving 3 hours costing 3 * 3 = 9.
  3. Subtract 2 + 3 = 5 covered hours from the 12 - 4 = 8 window hours, leaving 3 base hours costing 3 * 6 = 18, for a total of 20 + 9 + 18 = 47.

Complexity

Let k be the number of entries in overrides.

  • Time: O(k). We iterate through the k overrides once and perform O(1) arithmetic (max, min, subtraction, multiplication) per entry, completely independent of the span end_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 overrides list: covered_hours remains 0, so the full (end_time - start_time) span is charged at base_rate.
  • An override enclosing the entire window (e.g. [-5, 20, 3] on [0, 10)): Intersected length equals end_time - start_time, base_hours becomes 0, and every hour uses override_rate.
  • Overrides touching a boundary (e.g. [0, 4, 99] or [12, 16, 99] against [4, 12)): overlap_end == overlap_start, so overlap_end > overlap_start is False and 0 hours are charged.
  • Overrides completely outside the window: overlap_end < overlap_start, which clamps cleanly to 0 instead of a negative duration.
  • Discount or zero-price overrides (override_rate < base_rate or override_rate == 0): Covered hours still count toward covered_hours, preventing them from being charged base_rate a 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^12 hours): Python integers have arbitrary precision; in fixed-width languages such as C++ or Java, use 64-bit integers (long long / long) so hours * rate cannot overflow.

Common mistakes

  • Billing unclipped override durations. Using override_end - override_start charges hours outside [start_time, end_time) at override_rate and subtracts too many hours from base_hours (turning Example 2 into 19 instead of 47).
  • Off-by-one from closed-interval arithmetic (end - start + 1). [5, 9) covers hours 5, 6, 7, 8 (4 hours, not 5), and closed-interval math falsely charges 1 hour when two intervals merely touch at an endpoint.
  • Forgetting to clamp non-overlapping intervals to 0. Without if overlap_end > overlap_start, an outside override like [14, 18) against [4, 12) produces 12 - 14 = -2 hours, corrupting both covered_hours and override_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 in O(log k) time) of overrides whose start <= slice_start; before pricing each elementary slice [a, b), pop expired heap entries with end <= a, then charge (b - a) hours at the top heap rate (or base_rate only when the heap is empty, since an active discount override still supersedes base_rate). Sorting the O(k) cut points dominates at O(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 k disjoint overrides once in O(k log k) time and precompute two prefix sum arrays — running-total arrays that return the sum across any contiguous index slice [i..j] in O(1) time — one for override durations and one for override charges. Each query [start_time, end_time) then runs binary search in O(log k) time to locate the first override with override_end > start_time and the last override with override_start < end_time, manually clips at most those two boundary overrides, and looks up all strictly interior overrides in O(1) via the prefix sums for O(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 in O(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.1 or 0.01 exactly (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 with decimal.Decimal (or rational fractions.Fraction) and apply an explicit banker's rounding rule (ROUND_HALF_EVEN) once at invoice finalization.

Follow-up questions

Similar questions

More Crusoe interview questions

All 3 Crusoe questions →