KatInterview

Nearest Working Charger: Command Simulator with Great-Circle Math

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designdesignsimulationhaversine

Last updated

Process a batch of commands on a charging-station registry, with status updates, spherical distance and nearest-online lookups that break ties deterministically.

Charging Station Locator

You are writing the engine behind a map feature that sends drivers to the closest charging station that is currently working. Instead of a class, you implement one function that replays a batch of commands against a fresh, empty registry and returns one result per command.

Input

  • commands: a list of command names.
  • params: a list of the same length. params[i] is the list of arguments for commands[i].

If the two lists differ in length, raise ValueError.

Commands

Each station has an id (string), a latitude, a longitude (decimal degrees) and a status. The status is one of "online", "offline" or "maintenance".

CommandArgumentsEffectResult
add_station[station_id, lat, lon]Registers a station. It starts with status "offline".None
set_status[station_id, status]Changes a station's status.None
get_status[station_id]Reads a station's status.the status string
haversine_km[lat1, lon1, lat2, lon2]Computes the great-circle distance between two points. It does not touch the registry.a float
nearest_online[lat, lon] or [lat, lon, max_km]Finds the closest online station to the point.[station_id, distance], or None if nothing qualifies
k_nearest_online[lat, lon, k] or [lat, lon, k, max_km]Finds up to k closest online stations.a list of [station_id, distance] pairs, closest first (empty list if none)

Distance

Use the haversine formula with an Earth radius of exactly 6371.0 km. With angles converted to radians:

a = sin(dLat/2)^2 + cos(lat1) * cos(lat2) * sin(dLon/2)^2
distance = 2 * R * asin(sqrt(min(1, a)))

Here dLat = lat2 - lat1 and dLon = lon2 - lon1, both taken in degrees and then converted to radians. Cap a at 1.0 before the square root to guard against floating-point drift.

The haversine_km command returns the raw, unrounded float.

Routing rules

  • Only stations whose current status is "online" are candidates.
  • If max_km is given, keep only stations whose distance is less than or equal to max_km. If it is omitted, there is no limit.
  • Rank candidates by full-precision distance, ascending. If two distances are exactly equal, the lexicographically smaller station id comes first. Rank before rounding.
  • Each reported distance is rounded to 3 decimals with Python's round(d, 3).
  • k_nearest_online returns at most k entries, or fewer if fewer qualify. A k of 0 or less gives an empty list.
  • nearest_online behaves like k_nearest_online with k = 1, but returns the single pair itself, or None.
  • The query point of a routing command must have valid coordinates, otherwise raise ValueError.

Error handling

Processing stops at the first failing command, which raises the exception:

  • add_station with a latitude outside [-90, 90] or a longitude outside [-180, 180] raises ValueError. This check is done first. After it, an id that is already registered raises ValueError.
  • set_status with a status that is not one of the three allowed strings raises ValueError. This check is done first. After it, an unknown station id raises KeyError.
  • get_status with an unknown station id raises KeyError.
  • Any other command name raises ValueError.

Output

Return a list with one entry per command, in order, using the result column above. Distances and pairs are returned as lists, not tuples.

Constraints

  • Up to about 10^4 stations and 10^5 commands in total.
  • Latitude is in [-90, 90] and longitude is in [-180, 180] for valid coordinates.
  • Station ids are non-empty strings.
  • A linear scan per routing query is acceptable.

Examples

Example 1

Input: simulate_charging_stations(['add_station', 'add_station', 'add_station', 'set_status', 'set_status', 'set_status', 'set_status', 'nearest_online', 'k_nearest_online', 'nearest_online'], [['lyon-1', 45.764, 4.8357], ['geneva-2', 46.2044, 6.1432], ['turin-3', 45.0703, 7.6869], ['lyon-1', 'online'], ['geneva-2', 'online'], ['turin-3', 'online'], ['geneva-2', 'maintenance'], [45.8992, 6.1294], [45.8992, 6.1294, 3], [45.8992, 6.1294, 50]])

Output: [None, None, None, None, None, None, None, ['lyon-1', 101.352], [['lyon-1', 101.352], ['turin-3', 152.436]], None]

Example 2

Input: simulate_charging_stations(['add_station', 'set_status', 'get_status', 'haversine_km', 'haversine_km', 'haversine_km'], [['paris', 48.8566, 2.3522], ['paris', 'online'], ['paris'], [48.8566, 2.3522, 52.52, 13.405], [0, 0, 0, 180], [0, 179.5, 0, -179.5]])

Output: [None, None, 'online', 877.4633259175432, 20015.086796020572, 111.19492664455905]

Hints

Hint 1

Keep a single dictionary from station id to its latitude, longitude and current status, and handle each command with a simple branch.

Hint 2

The haversine formula needs radians everywhere, including the latitude and longitude differences. The antimeridian needs no special case because the sine term is periodic.

Hint 3

For routing, build (distance, id) pairs for online stations that pass the max_km filter, sort by that tuple at full precision, slice the first k, and only then round the distances.