Line Reflection Problem
Description
LeetCode Problem 356.
Given n points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.
In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points' set is the same as the reflected ones.
Note that there can be repeated points.
Example 1:
Input: points = [[1,1],[-1,1]]
Output: true
Explanation: We can choose the line x = 0.
Example 2:
Input: points = [[1,1],[-1,-1]]
Output: false
Explanation: We can't choose a line.
Constraints:
n == points.length1 <= n <= 10^4-10^8 <= points[i][j] <= 10^8
Follow up: Could you do better than O(n^2)?
Solution
Approach: The Line Must Be in the Middle
There is no need to try many candidate lines. If a mirror line x = c exists, it maps the leftmost point to a point that is just as far on the other side. That point must also be in the set, and it can't be beyond the rightmost point. So the leftmost and rightmost x-coordinates are mirror images of each other, and the line has to lie exactly halfway between them: c = (minX + maxX) / 2.
To stay with integers, use s = minX + maxX = 2c. The reflection of a point (x, y) over the line is (s - x, y). Put every point in a hash set, then check that each point's reflection is also in the set. If one is missing, no line works.
Repeated points cause no trouble. The question compares the set of points with the set of reflected points, so duplicates count only once, and the hash set ignores them automatically. Points that lie on the line are their own reflection.
Complexity: O(n) time on average (one pass to build the set and find minX and maxX, one pass to check). O(n) space for the set.
class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
# if a mirror line exists, it lies halfway between the leftmost and rightmost points
s = min(x for x, _ in points) + max(x for x, _ in points)
seen = {(x, y) for x, y in points}
# the mirror image of (x, y) is (s - x, y)
return all((s - x, y) in seen for x, y in points)