Amazon Interview Question
Software Engineer / Developerssmall correction u have to compare Q.max() to a[i]
and replace Q.max() with a[i] if a[i] < Q.max()
Hi!
Each x and y are grouped together as a single point. There are n such points. Hence O(n)
I think you should insert the element into the heap without comparing a[i] to Q.max(). Why are you comparing a[i] with Q.max()?
I am sorry, you need to compute the distances but not sort them :P You can use a linear implementation of an algorithm that searches K minimum elements in an Array.
abhijeet is right.
use the select algorithm (en.wikipedia.org/wiki/Selection_algorithm)to find the kth minimum element ,this takes o(n) time.after finding the kth minimum element iterate over the array to find all the elements less than the kth minimum element found.so overall complexity is o(n).
This is efficient in terms of run-time, but requires additional memory of O(n) (for selection algo). agnel.joel solution is memory optimal as it requires a heap of size O(k). if k is not close to O(n), heap approach is memory optimal.
guyz there are really smart people browsing this site,no wonder many problems dont have their solutions posted.
1. Create a Max Heap with the first k points using the distance factor..
2. For each remaining point, insert it in the Max Heap and then delete the max value from the heap.
3. The heap now contains the min k points.
4. This algorithm is O(n log m), where m is the number of points we are looking for.
1. Calculate the distances of each point once and store the distances in an array. O(N).
2. Now find the kth smallest distance in the array using Selection Rank algorithm. O(k).
3. Iterate over the N points again from the beginning and get all points whose distance is less than or equal to k and write them onto your k-size array. O(N).
considering N>>>k then total time complexity O(N).
Above solutions are too trivial, a better solution would be
- Brave Heart November 25, 2010compute x^2 + y^2 (no need sqrt!) and transform into another array. O(n)
Next,
build a Max Heap (Q) out of the first k elements in the array. ---> O(k)
For all elements from k+1..n , if a[i] < Q.min() ,
then Q.replace(Q.min() , a[i])
Q.downheap()
The above loop will take a total time of O(nlogk) in the worst case.
After the loop terminates, the contents of the heap is the k closest elements to the origin.
The total running time of this algorithm = O(n + nlogk)
If you use the trivial sorting method, it will take O(nlogn) . If n is very large, and if k is small, then you can see how inefficient sorting is.