Interview Question


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])

- gsharma34065 July 14, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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

- hb July 22, 2019 | Flag
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])

- Anonymous July 15, 2019 | Flag Reply
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])

- hb July 22, 2019 | Flag Reply
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)

- Anonymous July 30, 2019 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More