## Facebook Interview Question

Software Engineers**Country:**United States

Divide your map into a recursive grid.

Each cell contains either: a list of locations; or, if the number of locations in the cell exceeds some number N, it is divided into 4 more cells.

Search the cell the point lies in. Then, for each of 8 neighboring cells, if it is possible for a location to be closer than those already found, search that cell too.

Here is the gist:

1) Forget longitude and latitude, its just a weighted graph

2) Run any shortest path algo like Dijkstra algorithm to find shortest path of all node from the node in question

3) return the top 5 least paths

```
public class Solution {
public List<Node> getClosestNode(Node n, int closest) {
if(n == null || n.children() == null || n.children().size == 0 || closest <= 0) {
return new ArrayList<Node>();
}
Set<Node> settledNodes = new HashSet<Node>();
Map<Node, Node> predecessors = new HashMap<>();
PriorityQueue unsettledNodes = new PriorityQueue(new Comparator<Node>(){
@Override
public int compare(Node n1, Node n2) {
return n1.getDistance() - n2.getDistance();
}
});
unsettledNodes.add(n);
Map<Integer, List<Node>> distance = new TreeMap<>();
distance.put(0, new ArrayList<>());
distance.get(0).add(n);
while(!unsettledNodes.isEmpty()) {
Node source = unsettledNodes.poll();
settledNodes.add(source);
List<Node> neighbours = source.neighbours();
for(Node neighbour : neighbours) {
if(settledNodes.contains(neighbour )) {
continue;
}
int newDistance = this.getDistance(source) + n.getDistance();
if(this.getDistance(distance, neighbour ) > newDistance) {
if(!distance.hasKey(newDistance)) {
distance.put(newDistance, new ArrayList());
}
distance.get(newDistance).add(neighbour );
unsettledNodes.add(neighbour );
predecessors.put(source, neighbour );
}
}
}
return this.getClosestNode(distance, closest);
}
public List<Location> getClosestLocations(Map<Integer, List<Node>> map, int closest) {
List<Location> locations = new ArrayList<Location>();
for(EntrySet<Integer, List<Node>> entry : distance) {
for(Node n : entry.value()) {
if(locations.size() == closest) {
break;
}
locations.add(n.getLocation());
}
}
return locations;
}
public int getDistance(Map<Node, Integer> distance, Node to) {
return distance.hasKey(to) ? distance.get(to) : Integer.MAX_VALUE;
}
}
public class Node {
private List<Node> neighbours.....
private Location location;
private int distance;
}
```

This can be solved by maintaining a max heap of size 5. For any given point p2 from the list of n points, we determine and do following.

- Anonymous April 02, 20171) if the heap size is < 5 , add (distance of p2 from p1, point p2) pair to heap.

2) if heap size >= 5, we check if the distance of p2 from target point p1 is < distance of root node.

2a) if yes, we remove root node and add (distance of p2 from p1, point p2) pair to heap

2b) if no, ignore p2

In the end we will be left with 5 closest point to point p1.