Amazon Online Assessment (OA) - K Nearest Post Offices

Find the k post offices located closest to you, given your location and a list of locations of all post offices available.

Locations are given in 2D coordinates in [X, Y], where X and Y are integers.

Euclidean distance is applied to find the distance between you and a post office.

Assume your location is [m, n] and the location of a post office is [p, q], the Euclidean distance between the office and you is SquareRoot((m - p) * (m - p) + (n - q) * (n - q)).

K is a positive integer much smaller than the given number of post offices.

Input

The input consists of three arguments:

you: a list representing your location coordinates

post_offices: a list representing post offices' location coordinates

k: a positive integer much smaller than the given number of post offices

Output

Return 2D coordinates in [X, Y] of post offices located closest to you

Examples

Example 1:

Input:

you = [0, 0]

post_offices = [[-16, 5], [-1, 2], [4, 3], [10, -2], [0, 3], [-5, -9]]

K = 3

Output: [[-1, 2], [0, 3], [4, 3]]

Try it yourself

1from heapq import heapify, heappop
2from math import dist
3from typing import List
4
5def nearest_post_offices(you: List[int], offices: List[List[int]], k: int) -> List[List[int]]:
6    h = [(dist(you, o), o) for o in offices]
7    heapify(h)
8    return [heappop(h)[1] for _ in range(k)]
9
10if __name__ == '__main__':
11    you = [int(x) for x in input().split()]
12    offices = [[int(x) for x in input().split()] for _ in range(int(input()))]
13    k = int(input())
14    res = nearest_post_offices(you, offices, k)
15    for row in res:
16        print(' '.join(map(str, row)))
17

Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ