Healthy Region Registry and Nearest-Site Router
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate a command interpreter that registers sites, toggles their health, and answers nearest-healthy-site queries by great-circle distance, with strict validation and tie-breaking.
Healthy Region Registry and Nearest-Site Router
You are building the core of a traffic router for a worldwide hosting service. It keeps a registry of sites (regions) with their geographic positions and a health flag. It also answers queries asking which healthy site is closest to a given point on Earth.
Write a function that takes a list of text commands and returns a list of text results. Commands are processed in order, and each command produces exactly one output string. If a command is invalid for any reason, the registry must stay exactly as it was and the output for that command is ERROR.
Parsing rules
- Split each command on runs of whitespace (as Python's
str.split()does). The first token is the command name, and names are case-sensitive. - The number of tokens must match the command exactly, as listed below. A wrong token count, an unknown command name, or an empty or blank command gives
ERROR. - A "valid number" is any text that Python's
float()accepts, except thatnan,infand-inf(in any casing) are not valid. Range limits are inclusive.
Commands
REGISTER <id> <lat> <lon> (4 tokens)
Adds a new site whose health starts as UP.
<id>must be non-empty, consist only of letters and digits (the check Python'sstr.isalnum()performs), and not match any site already registered. Characters such as-or_make an id invalid.<lat>must be a valid number in[-90.0, 90.0].<lon>must be a valid number in[-180.0, 180.0].- Output
OKon success, otherwiseERROR.
SET_STATUS <id> <state> (3 tokens)
Changes the health of an existing site.
<id>must already be registered.<state>must be exactlyUPorDOWN(case-sensitive).- Setting a site to the state it already has is allowed and still gives
OK. - Output
OKon success, otherwiseERROR.
ROUTE <lat> <lon> (3 tokens)
Finds the closest site whose health is UP, measured from the query point.
<lat>must be a valid number in[-90.0, 90.0]and<lon>a valid number in[-180.0, 180.0].- At least one registered site must currently be
UP. - Output the
<id>of the closestUPsite. If several sites are at exactly the same computed distance, output the lexicographically smallest id. - Otherwise output
ERROR.
Distance
For points (lat1, lon1) and (lat2, lon2) given in degrees, with R = 6371.0:
dlat = radians(lat2) - radians(lat1)
dlon = radians(lon2 - lon1)
a = sin(dlat / 2)^2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2)^2
a = clamp(a, 0, 1)
dist = 2 * R * asin(sqrt(a))
Compare distances as the floating-point values this formula produces. Distances are tied only when these values are exactly equal.
Constraints
1 <= len(commands) <= 5000- At most 1000 distinct sites are ever registered.
- No input may cause an unhandled exception. Anything malformed must simply yield
ERROR.
Examples
Example 1
Input: run_region_commands(['REGISTER us-east 39.0438 -77.4874', 'REGISTER eu-west 53.3498 -6.2603', 'REGISTER us-east 40.0 -74.0', 'ROUTE 40.7128 -74.0060', 'SET_STATUS us-east DOWN', 'ROUTE 40.7128 -74.0060', 'SET_STATUS eu-west DOWN', 'ROUTE 40.7128 -74.0060'])
Output: ['ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR', 'ERROR']
Hints
Hint 1
Keep a dictionary from site id to its latitude, longitude and an up/down flag. Handle each command by checking its name and token count together, and fall through to ERROR otherwise.
Hint 2
Validate everything first (id rule, number parsing, ranges, state text) and only then write to the dictionary, so a failing command can never leave partial changes. Remember that float() accepts 'nan' and 'inf', which must be rejected.
Hint 3
For ROUTE, scan every UP site, compute the Haversine distance, and keep the best by the pair (distance, id). Convert degrees to radians before using trig functions, and clamp 'a' into [0, 1] before taking the square root and asin.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a small state machine over a dictionary mapping each site id to (lat, lon, is_up).
- Split each command into tokens and dispatch on the command name together with the token count. Anything that does not match a known shape outputs
ERROR. - For every command, validate all inputs before touching the dictionary. This covers the id rule, number parsing and ranges, and the state text. If any check fails, append
ERRORand skip the write, so failed commands never leave partial state. - For
ROUTE, scan allUPsites linearly. Compute the Haversine distance for each and keep the best by(distance, id). A candidate replaces the current best if its distance is strictly smaller, or equal with a lexicographically smaller id.
Why it is correct
- No side effects on failure: the only mutation in each branch happens after all validation has passed.
- Number parsing:
float()acceptsnanandinf, andnanfails every comparison, so a range check alone would let it through. Rejecting non-finite values withmath.isfinitecloses this gap. - Id rule:
str.isalnum()is false for ids containing-, so an id such asus-eastis rejected. The sample call therefore yields allERROR: both registrations fail, the duplicate fails,SET_STATUStargets unknown ids, andROUTEfinds noUPsite. - Deterministic ties: the scan picks the minimum of
(distance, id), which does not depend on dictionary order. - Numerical safety: rounding can push
aslightly above 1 for near-antipodal points, andasin(sqrt(a))would then fail, soais clamped to[0, 1]. - Units: angles are converted to radians before any trigonometric call.
Complexity
REGISTERandSET_STATUS: O(1) average per command.ROUTE: O(N) for N registered sites.- Total: O(C * N) time for C commands, which is at most about 5 million distance evaluations here. Space is O(N + C).
Reference solution
import math
from typing import List
def run_region_commands(commands: List[str]) -> List[str]:
sites = {} # id -> (lat, lon, is_up)
results = []
def parse_number(text, low, high):
try:
value = float(text)
except (TypeError, ValueError):
return None
if not math.isfinite(value) or value < low or value > high:
return None
return value
for command in commands:
if not isinstance(command, str):
results.append("ERROR")
continue
tokens = command.split()
if not tokens:
results.append("ERROR")
continue
name = tokens[0]
if name == "REGISTER" and len(tokens) == 4:
site_id, lat_text, lon_text = tokens[1:]
lat = parse_number(lat_text, -90.0, 90.0)
lon = parse_number(lon_text, -180.0, 180.0)
if (not site_id or not site_id.isalnum() or site_id in sites
or lat is None or lon is None):
results.append("ERROR")
else:
sites[site_id] = (lat, lon, True)
results.append("OK")
elif name == "SET_STATUS" and len(tokens) == 3:
site_id, state = tokens[1:]
if site_id not in sites or state not in ("UP", "DOWN"):
results.append("ERROR")
else:
lat, lon, _ = sites[site_id]
sites[site_id] = (lat, lon, state == "UP")
results.append("OK")
elif name == "ROUTE" and len(tokens) == 3:
lat = parse_number(tokens[1], -90.0, 90.0)
lon = parse_number(tokens[2], -180.0, 180.0)
if lat is None or lon is None:
results.append("ERROR")
continue
best_id = None
best_dist = None
lat1 = math.radians(lat)
for site_id, (s_lat, s_lon, is_up) in sites.items():
if not is_up:
continue
lat2 = math.radians(s_lat)
dlat = lat2 - lat1
dlon = math.radians(s_lon - lon)
a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
a = min(1.0, max(0.0, a))
dist = 2.0 * 6371.0 * math.asin(math.sqrt(a))
if (best_dist is None or dist < best_dist or
(dist == best_dist and site_id < best_id)):
best_dist = dist
best_id = site_id
results.append(best_id if best_id is not None else "ERROR")
else:
results.append("ERROR")
return results