Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top 5 Closest Locations

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Top 5 Closest Locations. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Life.Church receives location data as a JSON payload. Given the payload and a user's latitude and longitude, return the five closest Life.Church locations in ascending distance order.

Use the Haversine formula to calculate the great-circle distance between two latitude and longitude points. The payload is valid JSON with a top-level locations array. Each location contains a unique string id, a name, a numeric latitude, and a numeric longitude.

Because the payload may contain millions of locations, avoid sorting every location when selecting the result. Preserve the original input order when multiple locations have the same distance.

Formal Specification

Implement parse_top_locations(payload, user_lat, user_lon), where payload is a JSON string, user_lat and user_lon are numbers in degrees, and the return value is a list containing up to five original location objects. Results must be ordered from closest to farthest.

Constraints

  • 1 <= number of locations <= 1,000,000
  • -90 <= latitude <= 90
  • -180 <= longitude <= 180
  • Every location has a unique string id
  • The JSON payload is valid and contains the required fields
  • Equal-distance locations retain their original input order

Function Signature

def parse_top_locations(payload, user_lat, user_lon):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output