LeetCode Solutions

356. Line Reflection

Time: $O(n)$

Space: $O(n)$

			

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 vector<int>& 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 vector<int>& 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;
    }
  };
};
			

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;
  }
}
			

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))

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

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