Fleet Billing Ledger With Time-Dated Per-Minute Rates
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a bike-fleet billing ledger where each ride is priced at the rate active at its start, with rate changes, duplicate ride ids and an exact total.
A bike-share company bills its e-bikes by the minute. You are given a batch of ledger commands and must replay them in order, returning one result per command.
Implement bike_fleet_billing(operations, arguments). operations[i] is the command name and arguments[i] is its argument list. The two lists have equal length.
Commands
| Command | Arguments | Meaning |
|---|---|---|
register_bike | [bike_id, rate_per_minute] | Adds a bike whose starting price is rate_per_minute dollars per minute. This rate applies to any ride that starts before the bike's first scheduled change. |
update_rate | [bike_id, new_rate, effective_at] | Schedules a new per-minute rate for the bike, active for rides whose start time is at or after effective_at. |
record_ride | [ride_id, bike_id, start_time, end_time] | Logs one finished ride and adds its charge to the running total. |
get_total_cost | [] | Reports the running total of all charges so far. |
Rules
- Time units. Timestamps are integer Unix seconds. A ride lasts
end_time - start_timeseconds, which is(end_time - start_time) / 60minutes. Partial minutes are billed proportionally, with no rounding up or down. - Which rate applies. A ride is priced at the rate in effect at its own
start_time. That is the rate from the scheduled change with the largesteffective_atthat is<= start_time. If no such change exists, the bike's registration rate applies. The whole ride is charged at that single rate, even if another change would occur mid-ride. - Recording order does not matter for pricing. A ride recorded after later rate changes were scheduled is still priced by its own
start_time, not by the bike's latest rate. - No repricing. A charge is fixed when
record_rideis processed. Scheduling a change afterwards, even one with aneffective_atearlier than rides already recorded, does not alter the running total. It only affects rides recorded later. - Same effective time. If several
update_ratecommands for one bike use the sameeffective_at, the most recently processed one wins. - Duplicate rides.
ride_idvalues identify rides globally. Arecord_ridewhoseride_idwas already recorded is ignored completely and adds nothing. Only the first submission counts, even if its other arguments differ. - Exact money. Treat each rate as the decimal value it is written as (for example
0.2means exactly 0.20). Keep the running total exact, without rounding individual charges. Only when answeringget_total_cost, round the total to the nearest cent, with exact halves rounded up (away from zero). Format it with exactly two digits after the decimal point, such as"4.50"or"0.00".
Output
Return a list with one entry per command, in order. The entry is the formatted string for get_total_cost and None for every other command.
Constraints
1 <= len(operations) == len(arguments)- Command names are always one of the four above, and argument lists have the shapes shown.
- Every bike is registered (once) before any
update_rateorrecord_riderefers to it. 0 <= start_time <= end_time, all timestamps are integers, and a ride is shorter than one day.- Rates are non-negative numbers with at most a few decimal places.
- Ids are strings.
Examples
Example 1
Input: bike_fleet_billing(['register_bike', 'record_ride', 'get_total_cost', 'update_rate', 'record_ride', 'get_total_cost'], [['bike1', 0.2], ['r1', 'bike1', 0, 600], [], ['bike1', 0.3, 600], ['r2', 'bike1', 600, 900], []])
Output: [None, None, '2.00', None, None, '3.50']
Example 2
Input: bike_fleet_billing(['register_bike', 'update_rate', 'record_ride', 'record_ride', 'get_total_cost'], [['bike1', 0.2], ['bike1', 0.3, 600], ['late', 'bike1', 0, 600], ['late', 'bike1', 600, 900], []])
Output: [None, None, None, None, '2.00']
Hints
Hint 1
For each bike, keep its registration rate plus a sorted list of (effective_at, rate) changes, instead of one mutable rate value.
Hint 2
To price a ride, binary search for the last change whose effective_at is <= start_time. If there is none, use the registration rate. When inserting a change with an equal effective_at, place it after existing equal ones so the newest wins.
Hint 3
Floating-point sums can drift and round wrongly at half-cents. Use exact decimal arithmetic (built from the string form of each rate), add up rate * seconds / 60 without rounding, and round once, half-up, when formatting the total.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process the commands in order and keep three pieces of state:
- Per-bike rate timeline. Each bike has a registration rate and two parallel sorted lists: the
effective_attimes of scheduled changes and their rates. A single mutable "current rate" would be wrong, because a ride can be recorded after later changes were scheduled and must still use the rate that applied at its own start. - A set of recorded ride ids. A repeated
ride_idis skipped entirely, which makes recording idempotent. - An exact running total held as a
Decimal.
Scheduling a change. Insert the change at bisect_right(times, effective_at). This keeps the list sorted. For an equal timestamp, the new entry goes after the old ones.
Pricing a ride. Compute idx = bisect_right(times, start_time), the number of changes with effective_at <= start_time.
- If
idx == 0, use the registration rate. - Otherwise use the rate at position
idx - 1, the latest applicable change. Among equal timestamps this is the most recently submitted one, which gives the "latest wins" rule.
The charge is rate * seconds / 60, added to the total without rounding.
Reporting. Round the exact total to cents with ROUND_HALF_UP and format it with two decimals. Rounding only at query time avoids accumulated rounding error. Building each Decimal from str(rate) means 0.2 is exactly 0.20, which avoids binary floating-point artifacts and wrong half-cent decisions.
Why it is correct
- A ride's charge depends only on its own
start_time, the duration, and the timeline. The timeline lookup returns the change with the greatesteffective_at <= start_time, which is exactly the rate defined in the statement. - The charge is added once, when the ride is first recorded, so later changes cannot reprice it.
- The
seen_ridescheck ensures duplicates contribute nothing. - Decimal arithmetic is exact apart from the 28-digit default precision, far more than needed, so the half-up rounding at query time gives the expected cent value.
Complexity
Let k be the number of changes for a bike and n the number of commands.
register_bike: O(1).update_rate: O(log k) to find the position, plus O(k) for the list insertion.record_ride: O(log k).get_total_cost: O(1).- Total: roughly O(n log k) time plus insertion costs, and O(n) space.
Reference solution
from bisect import bisect_right
from decimal import Decimal, ROUND_HALF_UP
from typing import List, Optional
def bike_fleet_billing(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
# Timestamps are integer Unix seconds; rates are dollars per minute.
base_rate = {} # bike_id -> Decimal registration rate
change_times = {} # bike_id -> sorted list of effective_at
change_rates = {} # bike_id -> rates aligned with change_times
seen_rides = set()
total = Decimal("0")
results = []
for operation, args in zip(operations, arguments):
if operation == "register_bike":
bike_id, rate = args
base_rate[bike_id] = Decimal(str(rate))
change_times[bike_id] = []
change_rates[bike_id] = []
results.append(None)
elif operation == "update_rate":
bike_id, new_rate, effective_at = args
times = change_times[bike_id]
# bisect_right puts an equal timestamp after existing ones,
# so the latest submitted change wins at lookup time.
pos = bisect_right(times, effective_at)
times.insert(pos, effective_at)
change_rates[bike_id].insert(pos, Decimal(str(new_rate)))
results.append(None)
elif operation == "record_ride":
ride_id, bike_id, start_time, end_time = args
if ride_id not in seen_rides:
seen_rides.add(ride_id)
idx = bisect_right(change_times[bike_id], start_time)
rate = base_rate[bike_id] if idx == 0 else change_rates[bike_id][idx - 1]
seconds = end_time - start_time
total += rate * Decimal(seconds) / Decimal(60)
results.append(None)
elif operation == "get_total_cost":
amount = total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
results.append(format(amount, ".2f"))
else:
raise ValueError(f"Unknown operation: {operation}")
return results