top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Find 100 closest points to the origin in a Cartesian plane?

+5 votes
479 views

Given a million points in a Cartesian plane, design an algorithm to find 100 closest points to the origin.

posted Nov 18, 2013 by Mona Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Create max heap of size 100

calculate distance of first 100 points add it to the max heap, Now from here calculate distance from one by one and check weather we have to add it to the max heap or not we can do it by comparing top element with the current distance

if current distance < top element in max heap then remove top element in max heap and add current distance
else do nothing

loop the above if else condition for each of the million elements

Order:
Assuming there are n elements and we have to find top m elements then O(m+(n-m)logm) since m << n
Net order is O(nlogm)

answer Nov 25, 2013 by Raghu
Similar Questions
+6 votes

For example: It returns ‘b’ when the input is “abaccdeff”.

+5 votes
      40
      /\
     20 60
     /\  \
   10 30  80
      /   /\
     25  70 90
           \
           75

longest path 
25 30 20 40 60 80 70 75 
Answer
    25 ----> 75
+7 votes

You have a 2D matrix. Only two ZEROs in matrix.
Find the path from 1st zero to 2nd zero with least sum.

1       6       8       9       0       3

4       9       -5      5       11      13

8       9       44      23      15      -20

7       9       7       -13     14      11      

0       16      23      31      16      7

67      5       4       23      21      19

Answer

1       6       8       9       0  ----> 3
                                         |
4       9       -5      5       11      13
                                         |
8       9       44      23      15      -20
                                         |
7 <---- 9 <---- 7 <--- -13 <--- 14 <---  11     
|
0       16      23      31      16        7

67      5       4       23      21       19
+3 votes

Say the given string is ABC

Output should be ABC ACB BAC BCA CBA CAB

...