Leetcode

Line Reflection

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  bool isReflected(vector<vector<int>>& points) {
    int minX = INT_MAX;
    int maxX = INT_MIN;
    unordered_set<pair<int, int>, pairHash> seen;

    for (const auto& p : points) {
      const int x = p[0];
      const int y = p[1];
      minX = min(minX, x);
      maxX = max(maxX, x);
      seen.insert({x, y});
    }

    const int sum = minX + maxX;
    // (leftX + rightX) / 2 = (minX + maxX) / 2
    //  leftX = minX + maxX - rightX
    // rightX = minX + maxX - leftX

    for (const auto& p : points)
      if (!seen.count({sum - p[0], p[1]}))
        return false;

    return true;
  }

 private:
  struct pairHash {
    size_t operator()(const pair<int, int>& p) const {
      return p.first ^ p.second;
    }
  };
};

JAVA

class Solution {
  public boolean isReflected(int[][] points) {
    int minX = Integer.MAX_VALUE;
    int maxX = Integer.MIN_VALUE;
    Set<String> seen = new HashSet<>();

    for (int[] p : points) {
      final int x = p[0];
      final int y = p[1];
      minX = Math.min(minX, x);
      maxX = Math.max(maxX, x);
      seen.add(x + "," + y);
    }

    final int sum = minX + maxX;
    // (leftX + rightX) / 2 = (minX + maxX) / 2
    //  leftX = minX + maxX - rightX
    // rightX = minX + maxX - leftX

    for (int[] p : points)
      if (!seen.contains(sum - p[0] + "," + p[1]))
        return false;

    return true;
  }
}

Python

class Solution:
  def isReflected(self, points: List[List[int]]) -> bool:
    minX = math.inf
    maxX = -math.inf
    seen = set()

    for x, y in points:
      minX = min(minX, x)
      maxX = max(maxX, x)
      seen.add((x, y))

    sum = minX + maxX
    # (leftX + rightX) / 2 = (minX + maxX) / 2
    #  leftX = minX + maxX - rightX
    # rightX = minX + maxX - leftX

    return all((sum - x, y) in seen for x, y in points)