Problem
Consider a bounded box, we need to place circle's with double type center point (x,y) eg (1.4, 2.3), (4.25,53.3) etc.
Write definition of below function, which places the coin if not overlapping with already placed ones.
public boolean place(Double x, Double y)
inputs: circles center point (x, y)
output: boolean whether we can place the coin without overlapping with the existing coins.
My Solution
Within given 40mins of time, I was only able to come up with a x-axis sorted solution and binsearch on x-axis invoke coins falling within x-2, x+2 range linearly.
class CoinPlacement {
TreeSet<Pair<Double, Double>> sortedCoinsSet;
public CoinPlacement() {
this.sortedCoinsSet = new TreeSet<>();
}
//N coins placed:
//Q queries
//overal complexity: O(Q * (log N + N))
public boolean canPlace(Double x, Double y) {
Set<Pair<Double, Double>> subset = sortedCoinsSet.subSet(new Pair(x-2, y), new Pair(x+2, y)); //O(log N)
if (!subSet.isEmpty()) {
for (Pair<Double, Double> coins: subset) { //O(N)
if (overlap(coin, new Pair(x, y)) { // O(1)
return false;
}
}
}
sortedCoinsSet.add(new Pair(x, y)); //O(log N)
return true;
}
}Assume there is a overlap utility available something like
public boolean overlap(Pair<Doube, Double> coin1,
Pair<Doube, Double> coin2) {
double dx = coin1.getKey() - coin2.getKey();
double dy = coin1.getValue() - coin2.getValue();
double distanceSquared = dx * dx + dy * dy;
double minDistanceForOverlap = 2.0; // Diameter of a coin with radius 1
return distanceSquared < (minDistanceForOverlap * minDistanceForOverlap);
}Can anyone help me understand if there can be better approach than this using advanced DS to sort on both x and y axis can be done in logX * logY time?
Also please suggest, if this solution results in Hire/No Hire?


