Maximum Number of Visible Points

Compute angles relative to viewer, sort, sliding-window an arc of size `angle` — handle wraparound by doubling the array.

Hard
Time O(n log n) Space O(n)
LeetCode
5 min read
geometry sliding-window math sorting

Problem#

Standing at location, you can rotate but not move. You see any point within angle degrees of your facing direction. Some points may be at the same spot as you (always visible). Return the maximum count of visible points.

Examples#

  • points=[[2,1],[2,2],[3,3]], angle=90, location=[1,1]3.
  • points=[[1,0],[2,1]], angle=13, location=[1,1]1.

Constraints#

  • 1 <= points.length <= 10^5, 0 <= angle < 360.

Approach#

Count co-located points separately. For the rest, compute angle from viewer in degrees via atan2. Sort ascending; duplicate by adding 360 to each angle to handle wrap. Sliding window finds the longest run within angle.

Solution#

Maximum Number of Visible Points
class Solution {
public:
int visiblePoints(vector<vector<int>>& points, int angle, vector<int>& location) {
int same = 0;
vector<double> angs;
for (auto& p : points) {
int dx = p[0] - location[0], dy = p[1] - location[1];
if (dx == 0 && dy == 0) { ++same; continue; }
angs.push_back(atan2((double)dy, (double)dx) * 180.0 / M_PI);
}
sort(angs.begin(), angs.end());
int n = angs.size();
for (int i = 0; i < n; ++i) angs.push_back(angs[i] + 360.0);
int l = 0, best = 0;
for (int r = 0; r < (int)angs.size(); ++r) {
while (angs[r] - angs[l] > (double)angle + 1e-9) ++l;
best = max(best, r - l + 1);
}
return best + same;
}
};

Editorial#

Sorting angles plus the “doubled array” trick lets a sliding window naturally cross the 0/360 boundary. Co-located points must be handled out-of-band since their angle is undefined. The tiny epsilon 1e-9 makes the float comparison forgiving at the angle boundary.

Complexity#

  • Time: O(n log n) for the sort.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.