You are creating a website where people can track buses and figure out when to go to the station. The buses move between the stations in one direction. The goal is to find the station any bus is currently at or find how many stops away the nearest bus is to a requested station. Buses are never between stations; they are only stopped at a station.
Your task is to implement this class:
class BusTracker {// station list is the list of stations delimited by a hyphen (-)
// e.g. the station list can look like 1-2-3-4-5 and this will correspond to a map that looks like 1 -> 2 -> 3 -> 4 -> 5
// because buses only move in one direction, from left to right
// busLocations is the current list of buses and the stations they are currently at
// these two fields provide the input to figure out the next two functions
constructor(stationList, busLocations) {}
// given the buses flow in one direction, find how many stops away
// the next bus is to the provided station
public nearestBusToStation(stationId: string): number {return -1;}
// given a bus id, return the station the bus is currently at
public getBusLocation(busId: number): string {return "";}
};
Sample inputs – Expected outputs
For station map: "A-B-C-D-E-F-G-H-I"
And bus positions: {1: "B", 2: "E"}
busTracker.nearestBusToStation("A") // -1
busTracker.nearestBusToStation("B") // 0
busTracker.nearestBusToStation("C") // 1
busTracker.nearestBusToStation("D") // 2
busTracker.nearestBusToStation("E") // 0
busTracker.nearestBusToStation("F") // 1
busTracker.nearestBusToStation("G") // 2
busTracker.nearestBusToStation("H") // 3
busTracker.nearestBusToStation("I") // 4
busTracker.getBusLocation(1) // B
busTracker.getBusLocation(2) // E
This problem asks you to implement a BusTracker class for a one-way bus line. The station list is ordered from left to right, and each bus is always parked at a station. A good solution stores the station order in an array and the bus locations in a hash map. Then getBusLocation can be answered in constant time, while nearestBusToStation can be computed by comparing station positions and finding the closest bus that is at or before the requested station in the direction of travel. The main ideas are indexing, hash lookup, and directional distance computation.