You are given an arraylist of N coordinates or "spots" (Xi, Yi).
You can imagine all these points are placed on an infinitely large 2d array, where if the coordinate pair is given in the input arraylist, it is marked as 1, else it is 0.
You need to return an ArrayList of coordinates, where the coordinate pair at each index corresponds to the closest free element (marked 0) to the coordinate pair in the input arraylist.
Eg -
Input = [[0,3], [1,2], [2,2], [2,3], [3,2]]
This input can be visualised as -
[ 0, 0, 0, 1
0, 0, 1, 0
0, 0, 1, 1
0, 0, 1, 0]
Possible Outputs - [[0,2], [0,2], [2,1], [1,3], [3,2]]
or [[0,2], [1,1], [2,1], [2,4], [4,2]]
(Note that the matrix is actually infinitely large, so all out of bound indexes are actually 0)
There can be multiple closest coordinates for a given pair, any of them are considered a valid outputI gave a DFS approach as my first answer but it was of exponential time complexity so the interviewer was not happy.
I finally coded an O(n^3) approach, still he wasn't very happy.
He asked me to think of a linear approach.
Any idea on how to solve this linearly?