#1610
Maximum Number of Visible Points
HardArrayMathGeometrySliding WindowSortingSliding WindowSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach leverages sorting and the sliding window technique. By calculating angles and sorting them, we can efficiently determine how many points fall within the field of view using two pointers, reducing the time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the angle for each point relative to the observer's position.
- 2Step 2: Sort the angles in ascending order.
- 3Step 3: Duplicate the angles to handle the circular nature of the problem (i.e., angles > 360 degrees).
- 4Step 4: Use a sliding window to find the maximum number of points within the given angle range.
solution.py20 lines
1# Full working Python code
2import math
3from collections import deque
4
5def maxVisiblePoints(points, angle, location):
6 def calculate_angle(point):
7 dx = point[0] - location[0]
8 dy = point[1] - location[1]
9 return math.degrees(math.atan2(dy, dx)) % 360
10
11 angles = sorted(calculate_angle(p) for p in points)
12 angles += [a + 360 for a in angles] # Duplicate angles
13 max_count = 0
14 left = 0
15 for right in range(len(angles)):
16 while angles[right] - angles[left] > angle:
17 left += 1
18 max_count = max(max_count, right - left + 1)
19 return max_count
20ℹ
Complexity note: The time complexity is O(n log n) due to sorting the angles, and O(n) for storing the duplicated angles.
- 1Understanding angles in a circular manner is crucial.
- 2Using sorting and sliding window techniques can significantly reduce complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.