Nearest Working Charger: Command Simulator with Great-Circle Math
Data Structure DesignAuto-graded · 18 test casesLast 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 forcommands[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".
| Command | Arguments | Effect | Result |
|---|---|---|---|
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_kmis given, keep only stations whose distance is less than or equal tomax_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_onlinereturns at mostkentries, or fewer if fewer qualify. Akof0or less gives an empty list.nearest_onlinebehaves likek_nearest_onlinewithk = 1, but returns the single pair itself, orNone.- 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_stationwith a latitude outside[-90, 90]or a longitude outside[-180, 180]raisesValueError. This check is done first. After it, an id that is already registered raisesValueError.set_statuswith a status that is not one of the three allowed strings raisesValueError. This check is done first. After it, an unknown station id raisesKeyError.get_statuswith an unknown station id raisesKeyError.- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep one dictionary mapping each station id to its latitude, longitude and status. Walk through the commands in order and handle each with a plain branch.
- Registry commands.
add_stationvalidates the coordinates, then rejects duplicates, then stores the station as"offline".set_statuschecks the status string first and the id second.get_statusis a lookup that raisesKeyErrorfor unknown ids. Following the stated order of checks keeps the raised exceptions identical to the expected behavior. - Distance. Implement haversine with every angle converted to radians. The antimeridian needs no special handling because
sin(dLon/2)^2is periodic, so longitudes 179.5 and -179.5 come out 1 degree apart. Cappingaat 1 protectsasinfrom floating-point drift for nearly antipodal points. Thehaversine_kmcommand returns the raw float, with no rounding. - Routing. Collect
(id, distance)for every online station that passes the optional inclusivemax_kmfilter. Sort by(distance, id)using full-precision distances. This gives the lexicographic tie-break for free. Take the firstmax(0, k)entries and only then round each distance to 3 decimals. Rounding before ranking would turn near-ties into false ties.nearest_onlineis thek = 1case, returning the first pair orNone.
Why it is correct
Each command's effect depends only on the registry state built by earlier commands, so replaying them in order reproduces the intended behavior. The ranking key (distance, id) is a total order, so the output is deterministic. Rounding happens only at the output boundary, so it cannot affect which stations are chosen or in what order.
Complexity
add_station,set_statusandget_statustake O(1).- A routing query over n stations takes O(n) distance computations plus O(m log m) to sort the m candidates that pass the filters.
- Space is O(n) for the registry.
At much larger scale you would bucket stations in a geohash or S2 grid, or use a k-d tree on 3D unit vectors, and keep a separate index of online stations. The linear scan is fine for the constraints here.
Reference solution
import math
from typing import List
EARTH_RADIUS_KM = 6371.0
VALID_STATUSES = {"online", "offline", "maintenance"}
def _haversine(lat1, lon1, lat2, lon2):
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
return 2 * EARTH_RADIUS_KM * math.asin(math.sqrt(min(1.0, a)))
def simulate_charging_stations(commands: List[str], params: List[List]) -> List:
if len(commands) != len(params):
raise ValueError("commands and params must have equal length")
stations = {} # id -> [lat, lon, status]
results = []
def check_coords(lat, lon):
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
raise ValueError("coordinates out of range")
for cmd, args in zip(commands, params):
if cmd == "add_station":
sid, lat, lon = args
check_coords(lat, lon)
if sid in stations:
raise ValueError("duplicate station id")
stations[sid] = [lat, lon, "offline"]
results.append(None)
elif cmd == "set_status":
sid, status = args
if status not in VALID_STATUSES:
raise ValueError("unknown status")
if sid not in stations:
raise KeyError(sid)
stations[sid][2] = status
results.append(None)
elif cmd == "get_status":
sid = args[0]
if sid not in stations:
raise KeyError(sid)
results.append(stations[sid][2])
elif cmd == "haversine_km":
results.append(_haversine(*args))
elif cmd in ("nearest_online", "k_nearest_online"):
if cmd == "nearest_online":
lat, lon, *rest = args
k = 1
else:
lat, lon, k, *rest = args
check_coords(lat, lon)
max_km = rest[0] if rest else None
cands = []
for sid, (slat, slon, status) in stations.items():
if status != "online":
continue
d = _haversine(lat, lon, slat, slon)
if max_km is None or d <= max_km:
cands.append((sid, d))
cands.sort(key=lambda item: (item[1], item[0]))
picked = [[sid, round(d, 3)] for sid, d in cands[:max(0, k)]]
if cmd == "nearest_online":
results.append(picked[0] if picked else None)
else:
results.append(picked)
else:
raise ValueError("unknown operation")
return results