Line Reflection
Line Reflection is a medium arrays & hashing problem solved with the hash set lookup pattern.
The best approach, optimal (hash set of points, one lookup per point), runs in O(n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (find the line, scan for every mirror) up.
Problem
You are given n points on a flat plane, where points[i] = [x, y]. Decide whether some vertical line x = c works as a mirror for the whole set: reflect every point across that line, and the collection of reflected points is exactly the collection you started with.
Reflecting (x, y) across x = c gives (2c - x, y). The value c does not have to be an integer.
The points form a set: the same point may appear more than once in the input, and the copies count as a single point. A point that lies on the line is its own reflection.
Return true if such a line exists, otherwise false.
Examples
Example 1
- Input
points = [[1, 1], [-1, 1]]- Output
true- Why
- The vertical line x = 0 swaps the two points: (1, 1) lands on (-1, 1) and (-1, 1) lands on (1, 1).
Example 2
- Input
points = [[1, 1], [-1, -1]]- Output
false- Why
- The only possible mirror is x = 0, but it sends (1, 1) to (-1, 1), which is not in the set. A vertical mirror never changes a point's y.
Example 3
- Input
points = [[-2, 3], [4, 3], [1, 7], [1, 7], [0, -4], [2, -4]]- Output
true- Why
- The smallest x is -2 and the largest is 4, so the mirror is x = 1. (-2, 3) and (4, 3) swap, (0, -4) and (2, -4) swap, and (1, 7) sits on the line, so it maps to itself. The repeated (1, 7) changes nothing.
Constraints
1 <= points.length <= 10^4points[i].length == 2-10^8 <= points[i][0], points[i][1] <= 10^8
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 23 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (find the line, scan for every mirror) | O(n^2) | O(1) |
| Sort by row, match from both ends | O(n log n) | O(n) |
| Optimal (hash set of points, one lookup per point) | O(n) | O(n) |
1Brute force (find the line, scan for every mirror)
O(n^2)Each of the n points may scan all n points to find its mirror.O(1)Only a few counters besides the input.First pin down the line. Reflecting across x = c keeps y and sends x to 2c - x, and it reverses left and right, so the point with the smallest x has to land on the largest x. That forces 2c = minX + maxX: there is exactly one candidate line. Call that number sum. For every point (x, y), its mirror is (sum - x, y). Look for it by scanning the whole list. If any point has no mirror, the answer is false. Duplicates need no special care, because a point only has to find some copy of its mirror.
- Scan once for
minXandmaxX, and letsum = minX + maxX. - For each point
p, scan all points for aqwithq.y == p.yandq.x + p.x == sum. - If some
phas no suchq, return false; otherwise return true.
class Solution {
public boolean isReflected(int[][] points) {
int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
for (int[] p : points) {
minX = Math.min(minX, p[0]);
maxX = Math.max(maxX, p[0]);
}
long sum = (long) minX + maxX;
for (int[] p : points) {
boolean found = false;
for (int[] q : points) {
if (q[1] == p[1] && (long) q[0] + p[0] == sum) {
found = true;
break;
}
}
if (!found) return false;
}
return true;
}
}class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
min_x = min(p[0] for p in points)
max_x = max(p[0] for p in points)
total = min_x + max_x
for px, py in points:
found = False
for qx, qy in points:
if qy == py and qx + px == total:
found = True
break
if not found:
return False
return Trueclass Solution {
public:
bool isReflected(vector<vector<int>>& points) {
int minX = INT_MAX, maxX = INT_MIN;
for (auto& p : points) {
minX = min(minX, p[0]);
maxX = max(maxX, p[0]);
}
long long sum = (long long) minX + maxX;
for (auto& p : points) {
bool found = false;
for (auto& q : points) {
if (q[1] == p[1] && (long long) q[0] + p[0] == sum) {
found = true;
break;
}
}
if (!found) return false;
}
return true;
}
};function isReflected(points) {
let minX = Infinity, maxX = -Infinity;
for (const p of points) {
minX = Math.min(minX, p[0]);
maxX = Math.max(maxX, p[0]);
}
const sum = minX + maxX;
for (const p of points) {
let found = false;
for (const q of points) {
if (q[1] === p[1] && q[0] + p[0] === sum) {
found = true;
break;
}
}
if (!found) return false;
}
return true;
}2Sort by row, match from both ends
O(n log n)Sorting dominates; each row is then scanned once.O(n)The sorted copy and one row buffer.A vertical mirror never moves a point to another row, so each row (each y value) must be symmetric on its own, around the same line. Sort the points by y, then by x, so each row becomes a sorted run of x values. Drop repeated x values inside a row, since the input is really a set. In a symmetric row the smallest x pairs with the largest, the second smallest with the second largest, and so on, so walk two pointers inward and check that every pair adds up to sum = minX + maxX. A middle value left alone must sit on the line, which the same check covers (x + x == sum).
- Find
minXandmaxX; letsum = minX + maxX. - Sort a copy of the points by
y, then byx. - For each run of equal
y, copy its distinct x values intoxs. - With
lofrom the left andhifrom the right, requirexs[lo] + xs[hi] == sumwhilelo <= hi. - If every row passes, return true.
class Solution {
public boolean isReflected(int[][] points) {
int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
for (int[] p : points) {
minX = Math.min(minX, p[0]);
maxX = Math.max(maxX, p[0]);
}
long sum = (long) minX + maxX;
int[][] p = points.clone();
Arrays.sort(p, (a, b) -> a[1] != b[1] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
int n = p.length, i = 0;
while (i < n) {
int j = i;
while (j < n && p[j][1] == p[i][1]) j++;
int[] xs = new int[j - i];
int m = 0;
for (int k = i; k < j; k++) {
if (m == 0 || xs[m - 1] != p[k][0]) xs[m++] = p[k][0];
}
for (int lo = 0, hi = m - 1; lo <= hi; lo++, hi--) {
if ((long) xs[lo] + xs[hi] != sum) return false;
}
i = j;
}
return true;
}
}class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
min_x = min(p[0] for p in points)
max_x = max(p[0] for p in points)
total = min_x + max_x
pts = sorted(points, key=lambda q: (q[1], q[0]))
n, i = len(pts), 0
while i < n:
j = i
while j < n and pts[j][1] == pts[i][1]:
j += 1
xs = []
for k in range(i, j):
if not xs or xs[-1] != pts[k][0]:
xs.append(pts[k][0])
lo, hi = 0, len(xs) - 1
while lo <= hi:
if xs[lo] + xs[hi] != total:
return False
lo += 1
hi -= 1
i = j
return Trueclass Solution {
public:
bool isReflected(vector<vector<int>>& points) {
int minX = INT_MAX, maxX = INT_MIN;
for (auto& q : points) {
minX = min(minX, q[0]);
maxX = max(maxX, q[0]);
}
long long sum = (long long) minX + maxX;
vector<vector<int>> p = points;
sort(p.begin(), p.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] != b[1] ? a[1] < b[1] : a[0] < b[0];
});
int n = p.size(), i = 0;
while (i < n) {
int j = i;
while (j < n && p[j][1] == p[i][1]) j++;
vector<int> xs;
for (int k = i; k < j; k++) {
if (xs.empty() || xs.back() != p[k][0]) xs.push_back(p[k][0]);
}
for (int lo = 0, hi = (int) xs.size() - 1; lo <= hi; lo++, hi--) {
if ((long long) xs[lo] + xs[hi] != sum) return false;
}
i = j;
}
return true;
}
};function isReflected(points) {
let minX = Infinity, maxX = -Infinity;
for (const q of points) {
minX = Math.min(minX, q[0]);
maxX = Math.max(maxX, q[0]);
}
const sum = minX + maxX;
const p = [...points].sort((a, b) => (a[1] !== b[1] ? a[1] - b[1] : a[0] - b[0]));
const n = p.length;
let i = 0;
while (i < n) {
let j = i;
while (j < n && p[j][1] === p[i][1]) j++;
const xs = [];
for (let k = i; k < j; k++) {
if (xs.length === 0 || xs[xs.length - 1] !== p[k][0]) xs.push(p[k][0]);
}
for (let lo = 0, hi = xs.length - 1; lo <= hi; lo++, hi--) {
if (xs[lo] + xs[hi] !== sum) return false;
}
i = j;
}
return true;
}3Optimal (hash set of points, one lookup per point)
O(n)Two passes over the points, each step an O(1) average hash operation.O(n)The hash set holds up to n distinct points.Keep the same single candidate line, sum = minX + maxX, but make the mirror search O(1). While scanning for minX and maxX, put every point into a hash set. Then each point (x, y) only needs one membership test for (sum - x, y). Repeated points collapse into one set entry, which is exactly the set semantics the problem asks for. To store a pair as one number, combine it into a long key x * 400000001 + y; y spans fewer than 400000001 values, so different points always get different keys.
- In one pass, track
minX,maxXand addkey(x, y)for every point to a hash set. - Let
sum = minX + maxX. - For each point, if
key(sum - x, y)is not in the set, return false. - Return true.
class Solution {
public boolean isReflected(int[][] points) {
int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
Set<Long> seen = new HashSet<>();
for (int[] p : points) {
minX = Math.min(minX, p[0]);
maxX = Math.max(maxX, p[0]);
seen.add(key(p[0], p[1]));
}
long sum = (long) minX + maxX;
for (int[] p : points) {
if (!seen.contains(key(sum - p[0], p[1]))) return false;
}
return true;
}
private long key(long x, long y) {
return x * 400000001L + y;
}
}class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
min_x = min(p[0] for p in points)
max_x = max(p[0] for p in points)
seen = {(x, y) for x, y in points}
total = min_x + max_x
for x, y in points:
if (total - x, y) not in seen:
return False
return Trueclass Solution {
long long key(long long x, long long y) {
return x * 400000001LL + y;
}
public:
bool isReflected(vector<vector<int>>& points) {
int minX = INT_MAX, maxX = INT_MIN;
unordered_set<long long> seen;
for (auto& p : points) {
minX = min(minX, p[0]);
maxX = max(maxX, p[0]);
seen.insert(key(p[0], p[1]));
}
long long sum = (long long) minX + maxX;
for (auto& p : points) {
if (!seen.count(key(sum - p[0], p[1]))) return false;
}
return true;
}
};function isReflected(points) {
let minX = Infinity, maxX = -Infinity;
const seen = new Set();
for (const p of points) {
minX = Math.min(minX, p[0]);
maxX = Math.max(maxX, p[0]);
seen.add(p[0] + ',' + p[1]);
}
const sum = minX + maxX;
for (const p of points) {
if (!seen.has((sum - p[0]) + ',' + p[1])) return false;
}
return true;
}Edge cases to test
- A single point: the line through it reflects it onto itself, so the answer is true
- Repeated points: the input is a set, so a copy needs no partner of its own
- Points on the mirror line map to themselves
- The mirror can sit halfway between two integers, such as x = 0.5; compare minX + maxX with x + x' instead of dividing by two
- A matching x at a different y does not count: a vertical mirror keeps y unchanged
- minX + maxX can reach 2 * 10^8 and sum - x can reach 3 * 10^8, so use a wide integer type to be safe
Hints
Hint 1
A vertical mirror keeps y the same and sends x to 2c - x. Which point must the leftmost point be sent to?
Hint 2
The leftmost point has to land on the rightmost x, so the only possible line is c = (minX + maxX) / 2. There is nothing to search for.
Hint 3
To avoid halves, write the mirror of x as (minX + maxX) - x. Now the question is only: is every mirrored point in the set?
Hint 4
Put every point in a hash set, then check each point's mirror with one lookup.
FAQ
What is the best time complexity for Line Reflection?
Optimal (hash set of points, one lookup per point) runs in O(n) time and O(n) extra space. Two passes over the points, each step an O(1) average hash operation.
Which pattern does Line Reflection use?
It is a arrays & hashing problem that uses the hash set lookup pattern. Other problems with the same pattern: Longest Consecutive Sequence, Contains Duplicate, Fair Candy Swap.
Is there a brute force solution for Line Reflection?
Yes. Brute force (find the line, scan for every mirror) takes O(n^2) time and O(1) space. First pin down the line.
Which edge cases should I test for Line Reflection?
A single point: the line through it reflects it onto itself, so the answer is true; Repeated points: the input is a set, so a copy needs no partner of its own; Points on the mirror line map to themselves; The mirror can sit halfway between two integers, such as x = 0.5; compare minX + maxX with x + x' instead of dividing by two; A matching x at a different y does not count: a vertical mirror keeps y unchanged; minX + maxX can reach 2 10^8 and sum - x can reach 3 10^8, so use a wide integer type to be safe.