Clear solution using averages


  • 0

    For there to be a mirror along the y axis (vertical), there must be an equal number of points on the same height-line (on both sides). For all values grouped by 'y' value, there must be agreement on what the center x value (the average) should be.

    public class Solution {
        class Info {
            double count;
            double sum;
            
            Info() {
                this.count = 0;
                this.sum = 0;
            }
            
            void add(int value) {
                count++;
                sum += value;
            }
            
            double avg() {
                return sum / count;
            }
        }
        
        public boolean isReflected(int[][] points) {
            Map<Integer, Info> seen = new HashMap<>();
            
            for (int[] point : points) {
                int x = point[0];
                int y = point[1];
                
                if (!seen.containsKey(y)) {
                    seen.put(y, new Info());
                }    
                
                seen.get(y).add(x);
            }
            
            Double center = null;
            for (Info info : seen.values()) {
                if (center != null && center != info.avg()) {
                    return false;
                }
                
                center = info.avg();
            }
            
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.