## Google Interview Question

Software Engineers**Country:**United States

**Interview Type:**Phone Interview

The idea is to map the 2d points to some sort of fixed reference and only compare where it make sense, instead of comparing each point with all the other point, which makes it a N2 algorithm. So here is my take on this. Divide the entire grid into a chunk of k x k grid squares.

e.g. 1st squre(0,0)(0,k)(k,0)(k,k)

2nd squre (0,k)(k,k)(0,2k)(k.2k)

Then iterate over each point and assign a parent grid

CEIL(i/k) * k, CEIL(j/k)*k

Once we have the squres assigned, iterate over the points which belongs only to adjacent 8 sqaures. Rest will lay out of bound for any 2d points inside this grid. Then like minimum spanning tree algorithm, keep chaining the points.

You can find this in O(N) approach. Find the min from the array and the max from the array.

Now you should have your buckets like this:

bucket1: [min, min + k]

bucket2: [min + k + 1, min + k + 1 + k]

..

bucketN/K: [max - k,max]

Now, you start iteration over the array and find out which bucket the current number belongs to and add it in the corresponding bucket.

When the iteration is over, just check for those buckets whose count of items inserted is greater then 1.

As you said O(N^2) answer is pretty straight forward, for each element we check rest of the elements to see if their difference is less than K

One way to get time complexity down to O(N) or O(NlogN) by using a sliding window.

O(N) Time complexity if the input is sorted, else we sort the input and that gives O(NlogN) complexity.

The sliding window will work like below

`input: {1,2,5,10} k = 5`

We start with the first 2 elements.

`i = 0, j = 1`

If the difference between the first and last element (j - i) of the slide is <= k, we increase the sliding window to right (j++)

When the difference becomes > k, we increment i (i++)

Every time a new digit gets added to the window, it adds (j-i) number of additional groups to the total.

Example:

```
input: {1,2,5,10} K = 5
sliding window : [1,2] . total Groups: 1 [[1,2]]
since 2 - 1 <= 5 ==> j++;
sliding window : [1,2, 5] . total Groups: 3 [[1,2], [2,5],[1,5]]
since 5 - 1 <= 5 ==> j++;
sliding window : [1,2, 5, 10] . 10-1 > k so we increment i
sliding window : [2, 5, 10] . 10-2 > k so we increment i
sliding window : [5, 10] . total Groups: 3 [[1,2], [2,5],[1,5], [5,10]]
```

- divm01986 December 29, 2019