Amazon Interview Question
Country: United States
K-D Trees are best when it comes to coordinates.
We can find k nearest stars to a given star but not sure how to find k nearest stars when no star is given.
May be we can follow the below approach.
1. Select a region with maximum density distribution.
2. Find the centroid of this region.
3. Find the k nearest stars to the centroid using K-D trees implementation.
I believe this should work, any one having any second thoughts on this?
Use a max heap of k elements and add the stars based on the distance in 3D. You don't need to calculate the exact distance, just use this formula (x * x + y * y + z * z).
Try this if it is to find the k closest stars from a given coordinate.
public Star[] findKClosest (Star[] stars, Coordinate origin, int k) {
PriorityQueue<Star> pqueue = PriorityQueue<Star> (k, new StarComperator());
for (int i = 0; i < stars.length; i++) {
int dist = dist(origin, starts[i].coord());
if (pqueue.size() == k && pqeue.peek() > dist) {
pqueue.pop();
}
pqueue.add(dist);
}
return pqueue.toArray(new Star [0]);
}
An Amazon project manager(From Indian) asked me the same question in an interview.
Please note: 1 "huge set of stars as three dimensional coordinates" and 2 'k' has nothing to do with the distance by my understanding in the interview.
After the interview , I thought It might be have something with hash, because they always ask me 'hash this, hash that..' .
I had tried to use distance formula (x * x + y * y + z * z), but they said no. And even the closest
stars have a huge amount. I have no idea about K-Nearest Neighbors(KNN) and KD tree. But the question is how to deal with the huge amount stars by tree?
I totally agree with this.
They are looking for custom Hash implementation.
In Hashing, assume we are using alphabets to insert and hash algorithm is to insert the element equivalent to it's numeric value
[a=1,b=2,...z=26]
now nearest to any alphabet will have closest hash value.
So if you search closest hash value, you found nearest elements to given alphabet [here star]
I guess it is about employing K-Nearest Neighbors(KNN) algorithm to solve the problem.
- Murali Mohan July 10, 2013