{x}
blog image

Line Reflection

Solution Explanation:

This problem asks whether there exists a vertical line of symmetry for a given set of points. The solution efficiently determines this using a hash set (or equivalent data structure in different languages) to track points and a simple calculation to check for reflection.

Approach:

  1. Find Min and Max X: Iterate through the points to find the minimum and maximum x-coordinates (minX and maxX). This helps determine the potential line of reflection (x = (minX + maxX) / 2).

  2. Create a Point Set: Use a HashSet (or set in Python, unordered_set in C++, map in Go) to store the points efficiently. This allows for O(1) lookup time to check for the reflection of each point.

  3. Calculate the Midpoint and Check Reflections: Calculate the sum s = minX + maxX. For each point (x, y), its reflection across the line x = s / 2 will be (s - x, y). We check if this reflected point exists in the point set. If any point's reflection is missing, the condition for reflection symmetry is not met.

  4. Return the Result: If all points have their reflections present, the function returns true; otherwise, it returns false.

Time and Space Complexity:

  • Time Complexity: O(N), where N is the number of points. We iterate through the points once to find the min/max x values and once more to check for reflections. The hash set lookups are O(1) on average.

  • Space Complexity: O(N) to store the points in the hash set (or equivalent data structure).

Code Explanation (Python):

class Solution:
    def isReflected(self, points: List[List[int]]) -> bool:
        min_x, max_x = inf, -inf  # Initialize min and max x to infinity and negative infinity
        point_set = set()         # Use a set for efficient point lookup
 
        # Find min and max x and add points to the set
        for x, y in points:
            min_x = min(min_x, x)
            max_x = max(max_x, x)
            point_set.add((x, y))
 
        # Calculate sum of min and max x
        s = min_x + max_x
 
        # Check if each point's reflection exists in the set
        return all((s - x, y) in point_set for x, y in points)
 
 

The other language implementations follow the same logic, using the appropriate data structures for each language. The core idea remains consistent: efficient point storage and a linear-time check for reflections.