Is It Worth Writing Code That Resembles An Actual Codebase?

I was working on the [973. K Closest Points to Origin] problem and as I was writing this code, I was forgetting I was Leetcoding...
I wrote it like I was assigned this on the job and focused on readbility and testing over speed and effeciency -- since if needed -- speed and space can always be improved under 1 condition: the code is understandable :)

I wonder if the below code would be seen as a plus or a negative during a code review?

  1. It is not the fastest
  2. It is not the most space effecient
  3. Has way more lines of code than other solutions

  1. But it most resembles what you would read/write in an actual company's codebase

For example, the Pair class would most likely be moved to its own separate file called "Pair.java" while the distance function might even made public/protected and annotated with @IncreasedVisibilityForTesting.

Is it worth writing code like this in the interview or should the quick and dirty mentality prevail? What are your thoughts?


class Solution {
    public int[][] kClosest(int[][] points, int k) {
        // 1. Sort all the cordinates by their distances (min heap)
        PriorityQueue<Pair> values = new PriorityQueue<>();
        for (int[] cords : points) {
            values.add(new Pair(cords, distance(cords[0], cords[1])));
        }
        
        // 2. Normal Leetcode heap question, remove the 'k' number of min/max items requested
        List<int[]> output = new ArrayList<>();
        while (k > 0 && !values.isEmpty()) {
            output.add(values.poll().cords);
            k--;
        }
        return output.toArray(new int[output.size()][]);
    }
    
    // Helper method to make the function more clean/understandable
    private double distance(int x, int y) {
        double distance = Math.sqrt((Math.pow(x - 0, 2)) + (Math.pow(y - 0, 2)));
        System.out.println(distance);
        return distance;
    }
    
    
}

// Remember objects don't come with "Comparable" out of the box -> have to define that yourself
// Remember:
    // For small to large: a - b [OR] this - that
class Pair implements Comparable<Pair> {
    public int[] cords;
    public double distance;
    
    public Pair(int[] cords, double distance) {
        this.cords = cords;
        this.distance = distance;
    }
    
    public int compareTo(Pair b) {
        if (this.distance - b.distance < 0) {
            return -1;
        } else if (this.distance - b.distance > 0) {
            return 1;
        } else {
            return 1;
        }
    }
}
Comments (1)