## Interview Question

• 0

Country: United States

Comment hidden because of low score. Click to expand.
0
of 0 vote

I solved it with storing each point distance from (0,0) in a hashtable. And take minimum k elements from that table.

``````def distance(x, y):
return math.sqrt(x*x + y*y)

points = {(16,5), (-1,2), (4,3), (10,-2), (0,3), (-5,-9)}
k = 3
hashtable = {}

for i in points:
hashtable[distance(i[0],i[1])] = i

sorted_list = sorted(hashtable.items())
for i in range(k):
print(sorted_list[i][1])``````

Comment hidden because of low score. Click to expand.
0

1. What if there are two points with the same distance?
2. math.sqrt() not needed

Comment hidden because of low score. Click to expand.
0
of 0 vote

def distance(x, y)
return math.sqrt(x*x + y*y)

points = {(16,5), (-1,2), (4,3), (10,-2), (0,3), (-5,-9)}
k=3
hashtable = { }

for i in points:
hashtable[distance(i[0],i[1])] = i

sorted_list = sorted(hashtable.items())
for i in rank(k):
print(sorted_list[i][1])

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````points = [(16,5), (-1,2), (4,3), (10,-2), (0,3), (-5,-9), (2,1)]
points.sort(key = lambda p: p[0]*p[0] + p[1]*p[1])
print(points[:4])``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

Implement a min-heap and return first K points. Time Complexity: O(NlogN)
Space: O(N)

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.