KatInterview

Train Line Fare System with Dynamic Routes and Weekend Pricing

Data Structure DesignAuto-graded · 14 test cases
MediumAuto-gradedData Structure Designobject-oriented-designhash-mapsimulation

Last 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 true if successful
  • Returns false if 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_station to end_station
  • is_weekend is 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 None if 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