This is a Javascript implementation for the "Network Cabling" problem given on the second CodinGame challenge.

The article is the third in a series that I started with the goal of testing the feasibility of solving CodinGame challenges in Javascript. You can also check out the first and second solutions that I posted earlier.

On the face of it the problem seemed straight-forward enough: since all coordinates are integer values the vertical location that minimizes the amount of cable required will be the one that is as close as possible to all buildings. Intuitively this is the average vertical coordinate. The only catch is that since the coordinates are all integers, and the answer is supposed to be an integer value as well, we'd have to consider both integer points closest to the real average value.

This results in a nice O(n) solution that computes the minimum and maximum horizontal coordinates, as well as the average vertical point. Another linear pass gives the final value.