Skip to content

356. Line Reflection 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.contains({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;
    }
  };
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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)