Katkat

Calculate charge with a single price override

CrusoeSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to handle overlapping time intervals and apply conditional overrides to calculate the total charge for a billing period.

Problem Statement

You are building a billing system that calculates the total cost for a service over a given period. The service has a base_rate per hour. Occasionally, a special override price is applied for a specific time range. If an override interval overlaps with the billing period, the override price takes precedence during the overlapping duration; otherwise, the base rate applies.

You are given:

  • start_time, end_time: The bounds of the billing period (inclusive of start, exclusive of end).
  • base_rate: The standard price per hour.
  • overrides: A list of tuples (override_start, override_end, override_rate).

Implement the function calculate_total_charge(start_time, end_time, base_rate, overrides).

Constraints

  • start_time < end_time.
  • Overrides may be partially or fully outside the billing period.
  • Overrides do not overlap with each other.
  • Time units are integers.

Examples

# Example 1
# Period: 0 to 10, Base: $10/hr
# Override: 2 to 5, Rate: $20/hr
# Logic: (2 hours * $10) + (3 hours * $20) + (5 hours * $10) = 20 + 60 + 50 = 130
calculate_total_charge(0, 10, 10, [(2, 5, 20)]) # Output: 130

# Example 2
# Period: 0 to 10, Base: $5/hr
# Override: 8 to 12, Rate: $2/hr
# Logic: (8 hours * $5) + (2 hours * $2) = 40 + 4 = 44
calculate_total_charge(0, 10, 5, [(8, 12, 2)]) # Output: 44

Hints

Hint 1

Consider clipping each override interval to the bounds of the billing period to ignore portions that fall outside.

Hint 2

Calculate the total duration covered by all valid overrides and subtract that from the total period length to find how much time is billed at the base rate.

Hint 3

Sort the overrides by their start time to simplify the logic, though identifying overlaps via intersection logic is sufficient.

Follow-up questions

  • How would you modify the solution if multiple overrides could overlap each other, and the highest rate always takes precedence?
  • If the billing period was very long and you had millions of overrides, how would you optimize the lookup efficiency?
  • How would you handle cases where the time intervals are provided as floating-point numbers instead of integers?