Amazon coding interview question - challenge for everyone
what is the challenge?
- make a program that takes a list of positions in (x, y) format.
- it should then return the K closest positions to (0, 0).
- you can use any list of positions and any k you like.
i have two solutions, the first is simpler but less efficient than the second.
if you finish it and want to challenge yourself further, try make it as time efficient as you can.
My solution was to first check if the point was along an axis. If it was along the X-axis, the distance would be the X value. If it was on the Y-axis, the distance would be the Y value.
If it is neither, then the program will find the hypotenuse of a right triangle with points (0, 0), the given point, and the X-line on which it is. The program then sorts the lengths from lowest to highest and checks all values in the new list of lengths to see if any of them have the same value as the Kth item in the list. All of the points with lengths equal to the one at index 0 get are appended to a list.
Let me know if I need to fix something.
@ObiVibKenobi hey, i just checked it out and is some pretty neat code! Although i think you misunderstood the question slightly, i think i worded it badly in the post, the k value is for returning that many closest positions, so if k was 3 then it would return the 3 closest positions to (0,0) hope that clears things up abit my bad for the bad explanation in the post lmao
Oh and id recomend trying to work on paper first and try simplify the problem as much as possible, so what i did was realise that if you sum the absolute values for the x and y then that would be a relative distance, therefore you do not Have to get the hypotenuse but theres of course nothing wrong with the way you did it!