Given a set of n points (xi, yi) in 2D coordinate. Each point has some weight wi. The task is to check whether a line at 45 degree can be drawn so that sum of weights of points on each side are equal.
Input : x1 = -1, y1 = 1, w1 = 3 x2 = -2, y2 = 1, w2 = 1 x3 = 1, y3 = -1, w3 = 4 Output : Yes Input : x1 = 1, y1 = 1, w1 = 2 x2 = -1, y2 = 1, w2 = 1 x3 = 1, y3 = -1, w3 = 2 Output : No
First, let’s try to solve above problem for a vertical line i.e if a line x = i can divide the plane into two part such that the sum of weight at each side is equal.
Observe, multiple points with the same x-coordinate can be treated as one point with weight equal to the sum of weights of all points with the same x-coordinate.
Now, traverse through all x-coordinates from the minimum x-coordinate to maximum x-coordinate. So, make an array prefix_sum, which will store the sum of weights till the point x = i.
So, there can be two options for which the answer can be ‘Yes’:
- Either prefix_sum[1, 2, …, i-1] = prefix_sum[i+1, …, n]
- or there exist a point i such that a line passes somewhere in between
x = i and x = i+1 and prefix_sum[1, …, i] = prefix_sum[i+1, …, n],
where prefix_sum[i, …, j] is the sum of weight of points from i to j.
int is_possible = false; for (int i = 1; i < prefix_sum.size(); i++) if (prefix_sum[i] == total_sum - prefix_sum[i]) is_possible = true if (prefix_sum[i-1] == total_sum - prefix_sum[i]) is_possible = true
Now, to solve for a line at 45 degrees, we will rotate each point by 45 degrees.
Refer: 2D Transformation or Rotation of objects
So, point at (x, y), after 45 degree rotation will become ((x – y)/sqrt(2), (x + y)/sqrt(2)).
We can ignore the sqrt(2) since it is the scaling factor. Also, we don’t need to care about y-coordinate after rotation because a vertical line cannot distinguish between the point having the same x-coordinate. (x, y1) and (x, y2) will lie to the right, left or on any line of the form x = k.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.