Line Reflection

medium hash set math

Problem

Given n points in 2D, return whether there exists a vertical line that reflects all points onto themselves.

Inputpoints = [[1,1],[-1,1]]
Outputtrue
The y-axis (x = 0) is the reflection line — each point's mirror is the other.

def is_reflected(points):
    xs = [p[0] for p in points]
    s = min(xs) + max(xs)
    seen = {(p[0], p[1]) for p in points}
    return all((s - x, y) in seen for x, y in seen)
function isReflected(points) {
  const xs = points.map(p => p[0]);
  const s = Math.min(...xs) + Math.max(...xs);
  const seen = new Set(points.map(p => p[0] + "," + p[1]));
  return points.every(([x, y]) => seen.has((s - x) + "," + y));
}
class Solution {
    public boolean isReflected(int[][] points) {
        int lo = Integer.MAX_VALUE, hi = Integer.MIN_VALUE;
        Set seen = new HashSet<>();
        for (int[] p : points) {
            lo = Math.min(lo, p[0]); hi = Math.max(hi, p[0]);
            seen.add(p[0] + "," + p[1]);
        }
        int s = lo + hi;
        for (int[] p : points) if (!seen.contains((s - p[0]) + "," + p[1])) return false;
        return true;
    }
}
bool isReflected(vector>& points) {
    int lo = INT_MAX, hi = INT_MIN;
    set> seen;
    for (auto& p : points) { lo = min(lo, p[0]); hi = max(hi, p[0]); seen.insert({p[0], p[1]}); }
    int s = lo + hi;
    for (auto& p : points) if (!seen.count({s - p[0], p[1]})) return false;
    return true;
}
Time: O(n) Space: O(n)