Amazon Interview Question
Software Engineer / DevelopersTeam: Amazon Video
Country: UK
Interview Type: In-Person
Suppose you are in one location and they gave the 20 ATM's list, We have to invoke getDistance() 20 times to get the distance of all the ATM's, then do the sort and pick the first K locations? Am i right? O(1) for each ATM distance, O(n) for get all the distances and O(n) to select the K ATM centers, am i right?
PriorityQueue can also be used.
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class PrioRQueueExample {
public static void main(String[] args){
PriorityQueue<Double> pq = new PriorityQueue<Double>((x,y)-> {Double z = y-x;return z.intValue(); });
PrioRQueueExample pqe = new PrioRQueueExample();
//Number of ATMs to return i.e. K
int num_ATMs = 3;
double curr_loc = 0.00;
Map<String,Double> nallATMLocs = new HashMap<String,Double>();
//Map of ATM names and their distance co-ordinates
nallATMLocs.put("atm1",45.0);
nallATMLocs.put("atm2",78.0);
nallATMLocs.put("atm3",54.0);
nallATMLocs.put("atm4",64.0);
nallATMLocs.put("atm5",35.0);
nallATMLocs.put("atm6",42.0);
nallATMLocs.put("atm7",57.0);
nallATMLocs.put("atm7",1.00);
nallATMLocs.forEach((atm,dist) ->{if(pq.size() < num_ATMs){
pq.add(pqe.getLocation(curr_loc,dist));}
else{
if( pq.peek() > pqe.getLocation(curr_loc,dist)){
pq.poll();
pq.add(pqe.getLocation(curr_loc,dist));
}
}
});
pq.forEach(atmLoc -> System.out.println(atmLoc));
}
private double getLocation(double curr,double atm){
return atm - curr;
}
}
One solution can be using the PriorityQueue
- FiguringOut June 25, 2017