The REGISTER and SET_HEALTHY parts were fine, just bookkeeping.
Start by clarifying the exact command formats, validation rules, and expected outputs, then design a data structure to store router information (location, health status) and implement each command handler with proper error checking. For the ROUTE command, compute Haversine distances from the source router to all healthy routers, select the nearest one, and handle ties or no healthy routers appropriately.
Pro tip: Before coding, walk through a few example commands with the interviewer to confirm edge cases like duplicate registrations, invalid coordinates, and tie-breaking in distance calculations. This shows you think about correctness and edge cases upfront, which is highly valued at Amazon.
Ask questions to understand the exact command syntax, validation rules (e.g., valid coordinates, duplicate IDs), and expected output for each command. Confirm how ties in distance should be resolved and what to do when no healthy routers exist.
Choose appropriate data structures to store router information, such as a hash map for quick lookup by router ID, and possibly a list or set for healthy routers. Consider how to efficiently retrieve all healthy routers for distance calculations.
Write functions for each command: REGISTER (validate and add router), SET_HEALTHY (update health status), DISTANCE (compute Haversine distance between two routers), and ROUTE (find nearest healthy router from source). Ensure each returns the correct output string or error message.
Implement the Haversine formula to compute distances between routers. For ROUTE, iterate over healthy routers, compute distances, and select the one with the smallest distance, handling ties and no healthy routers as per requirements.
Test with provided examples and additional edge cases (e.g., invalid commands, duplicate registrations, routers with same coordinates). Ensure outputs match expected format and all validation rules are enforced.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.