Line Reflection

Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points.

Example

Example1

Input: [[1,1],[-1,1]]
Output: true

Example2

Input: [[1,1],[-1,-1]]
Output: false

Challenge

Could you do better than O(n2)?

public class Solution {
    public boolean isReflected(int[][] points) {
        int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
        Set<String> set = new HashSet<>();
        for (int[] p : points) {
            minX = Math.min(minX, p[0]);
            maxX = Math.max(maxX, p[0]);
            String str = Double.toString((double) p[0]) + " " + Double.toString((double) p[1]);

            set.add(str);
        }
        // This will be our reflection line
        double mid = (double) ((minX + maxX)) / 2.0;

        for (int[] p : points) {
            double dist = Math.abs((double) p[0] - mid);
            String key = Double.toString(p[0] > mid ? (double) p[0] - 2 * dist : (double) p[0] + 2 * dist) + " "
                    + Double.toString((double) p[1]);
            if (!set.contains(key))
                return false;
        }
        return true;
    }
}

Last updated