Train Line Fare System with Dynamic Routes and Weekend Pricing
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests object-oriented design, index lookups, dynamic data structure updates, and conditional pricing rules in a fare calculation system.
You are building a fare calculation engine for a metro train line. The line consists of stations arranged in sequence, where traveling between any two consecutive stations costs exactly 1 unit. The total fare for a journey is the sum of all segments traveled.
For example, if the line is arranged as A → B → C → D → E, then:
- A trip from A to E passes through 4 segments and costs 4
- A trip from C to A passes through 2 segments and costs 2
- A trip from B to B costs 0 (no segments traveled)
Your system must process a sequence of operations on an initially defined route:
Operation: ["add_station", station_name]
- Appends a new station to the end of the current line
- Returns
trueif successful - Returns
falseif the station name already exists on the line (duplicate names are rejected)
Operation: ["fare", start_station, end_station, is_weekend]
- Computes the fare for a trip from
start_stationtoend_station is_weekendis a boolean indicating whether the trip occurs on a weekend- On weekends, the fare is capped at a maximum value (provided as input)
- Returns the fare as an integer, or
Noneif either station does not exist on the line
Process all operations in order and return a list of results.
Constraints
- 1 ≤ initial number of stations ≤ 100
- 1 ≤ number of operations ≤ 1000
- 1 ≤ weekend_cap ≤ 100
- Station names are non-empty strings containing only uppercase letters
- All station names in the initial route are unique
- The fare between any two adjacent stations is always 1
- Direction does not affect fare (A to B costs the same as B to A)
Examples
Example 1
Input: compute_train_fares(['G', 'U', 'H', 'K', 'I'], [['fare', 'G', 'I', False], ['fare', 'I', 'G', True], ['fare', 'H', 'H', True]], 3)
Output: [4, 3, 0]
Example 2
Input: compute_train_fares(['G', 'U'], [['add_station', 'H'], ['fare', 'G', 'H', False], ['add_station', 'U'], ['fare', 'H', 'G', True]], 2)
Output: [True, 2, False, 2]
Hints
Hint 1
Build a position index mapping each station name to its index in the route for constant-time fare lookups
Hint 2
The fare between two stations is the absolute difference of their positions in the sequence
Hint 3
Rebuild or update your index after each add_station operation, checking for duplicates before insertion
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that stations form a linear sequence, and the fare between any two stations equals the number of segments (edges) between them. Since each segment costs 1 unit, the fare is simply the absolute difference between the positions of the two stations in the route.
Key components:
-
Position index: Map each station name to its zero-based index in the route list. This enables constant-time fare calculation through index subtraction.
-
Dynamic station addition: When adding a station, first check if it already exists in the route (reject duplicates). If valid, append it to the end and it becomes available for subsequent fare queries.
-
Weekend pricing cap: Apply a maximum fare limit when the
is_weekendflag is true. Compare the computed base fare against the cap and take the minimum. -
Invalid station handling: If either the start or end station is not found in the current route, return
Noneto signal an error condition.
Why this works:
In a linear sequence, distance is simply positional difference. Since fare is proportional to distance with a constant cost per segment, abs(position[start] - position[end]) directly gives the fare. The position map can be rebuilt on each fare query (acceptable for the given constraints) or maintained incrementally after each add operation.
Complexity
- Time: O(n) per fare query to build the position map, where n is the current number of stations. O(n) per add_station to check for duplicates. For k operations on a route with up to n stations, total time is O(k·n).
- Space: O(n) to store the route and position map.
For better performance with many fare queries, maintain a persistent position map and update it in O(1) when adding stations, reducing fare queries to O(1).
from typing import List, Optional
def compute_train_fares(stations: List[str], operations: List[List], weekend_cap: int) -> List:
route = list(stations)
results = []
for op in operations:
op_type = op[0]
if op_type == "add_station":
new_station = op[1]
if new_station in route:
results.append(False)
else:
route.append(new_station)
results.append(True)
elif op_type == "fare":
start, end, is_weekend = op[1], op[2], op[3]
position_map = {station: idx for idx, station in enumerate(route)}
if start not in position_map or end not in position_map:
results.append(None)
else:
base_fare = abs(position_map[start] - position_map[end])
final_fare = min(base_fare, weekend_cap) if is_weekend else base_fare
results.append(final_fare)
return results