Google Interview Question for Software Engineers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
Brute-force solution: Maintain disjoint sets. Compute Euclidean distance between each pair of points and update the parent of each point’s disjoint set (using union by rank and path compression). Time complexity: O(N^2). Space: O(N)
**/

/**Optimal Solution: Use closest points algorithm to solve this problem in O(NlogN) time and O(N) space**/

class Point {
	int x;
	int y;
}

float euclidDistance(Point a, Point b) {}

int find(int[] ds, int idx) {
	Stack<Integer> stack = new Stack<Integer>();
	while (ds[idx] != idx) {
			stack.push(idx);
			idx = ds[idx];
	}
	while (!stack.isEmpty()) {
		int top = stack.pop():
		ds[top] = idx;
	}
	return idx;
}

int pointGroups(Point[] pts, float k) {
	int[] sets = new int[pts.length]//disjoint sets
	for (int i = 0; i < sets.length; i++) {
		sets[i] = i;
	}

	// Sort points by ascending x coordinate
	pts.sort(new Comparator() {
		public int compare(Point first, Point sec) {
			return first.x - sec.x
		}

	}
	
	pointsGroupHelp(pts,0,pts.length - 1, k, ds);
	//Apply path compression and count the total number of groups
	int count = 0;
	boolean[] seenGroup = new boolean[ds.length];
	for (int i = 0; i < ds.length; i++) {
		int p = find(ds,i);
		if (!seenGroup[p]) {
			count++;
			seenGroup[p] = true;
		}
	}
	return count;	
}

void bruteForce(Point[] pts, int start, int end, int[] ds, float k) {
	for (int i = start; i <= end; i++) {

		for (int j = i + 1; j <= end, j++) {
				float d = euclidDistance(pts[i],pts[j]);
				if (d <= k) {

						int minParent = Math.min(ds[i],ds[j]);
						int maxParent = Math.max(ds[i],ds[j]);
						ds[maxParent] = minParent;
				}
		}
	}
}

void pointsGroupHelp(Point[] pts,int start,,int end, float k, int[] ds) {
	if ((end - start + 1) <= 3) {
			bruteForce(pts,start,end,ds,k);
			return;
	}

	int mid = start + (end - start) / 2;
	
	int midX = pts[mid].x; //mid line

	pointsGroupHelp(pts,start,mid,k,ds); // group together all points <= k distance that lie to the left of mid line
	pointsGroupHelp(pts,mid + 1, end, k, ds); // group together all points <= k distance that lie to the right of mid line

	// Find subarray of points that are within <=k units away from midline and group pairs whose distance is <= k
	int stripStart = -1;
	int stripEnd = stripStart;
	for (int i = start; i <= end; i++) {
		if (Math.abs(pts[i].x - midX) <= k) {
			stripStart = stripStart == -1 ? i : stripStart;
			stripEnd = i;
		}
	}
	bruteForce(pts,stripStart,stripEnd,k,ds);
}

- divm01986 December 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

gjgjg

- khkh December 02, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

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.

- Confused Aatma December 03, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Order : O(N)
However, if all the 2d points are packed with in these 9 squres, then a further division will reduce the number of iteration within the points.

- Confused Aatma December 03, 2019 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

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.

- Abhishek J December 11, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

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]]

- Saurabh January 07, 2020 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More