I was rejected after a tech screening for the following code. I mainly struggled to make the code 'production ready'. I was running out of time so I did not create a class for testing. How could I have improved this code?
/*
Problem
Imagine you are building a friend locator app.
Given your current position identified on a bidimensional plane as (0,0) and a list of friend locations,
each identified by a (x,y) pair, return the k closest friends to your current location.
For simplicity, you can compute the distance between you and your friends using the Euclidean distance formula ( d = sqrt(x^2 +y^2) ).
Given a list of friend locations [[1,3], [-2,2]], K = 1
Output: [[-2,2]]
*/
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution {
static class Pair{
int x, y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
/*
d -> cords
time - O(n)
space - O(n)
*/
public static List<Pair> closestFriends(List<Pair> list, int k){
SortedMap<Double, Pair> map = new TreeMap<>();
List<Pair> results = new ArrayList<Pair>();
int i =0;
for(Pair pair : list){
double d = distance(pair);
map.put(d, pair);
}
for(Map.Entry<Double, Pair> entry : map.entrySet()){
if(i < k){
results.add(entry.getValue());
i++;
}
}
return results;
}
public static double distance(Pair p){
return Math.sqrt(p.x*p.x + p.y*p.y);
}
public static void main(String[] args) {
ArrayList<Pair> cords = new ArrayList<>();
cords.add(new Pair(1,3));
cords.add(new Pair(-2,2));
cords.add(new Pair(0,10));
cords.add(new Pair(-2,2));
cords.add(new Pair(1,3));
cords.add(new Pair(-2,2));
int k =1;
/*
empty list of cords
negative k
list list of cords
test cases for distance - correct calculation
*/
List<Pair> res = closestFriends(cords, k);
for(int i =0; i < res.size(); i++){
System.out.println(res.get(i).x + "," +res.get(i).y);
}
}
}
class Solution {
is something I'd expect to see in a programming-challenge, not in production code. Was this provided by the company? \$\endgroup\$return cords.stream().sorted(Comparator.comparingDouble(p -> Math.hypot(p.x, p.y))).limit(k).collect(Collectors.toList())
. \$\endgroup\$