#3143
Maximum Points Inside the Square
MediumArrayHash TableStringBinary SearchSortingHash MapArray
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 sorts points based on their distance from the origin and uses a sliding window technique to efficiently count unique tags within a square of varying side lengths.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the maximum distance for each point using max(abs(x), abs(y)) and store it along with the corresponding tag.
- 2Step 2: Sort the points based on this maximum distance.
- 3Step 3: Use a sliding window to check how many unique tags fit within the current square size defined by the maximum distance of the point at the right end of the window.
solution.py24 lines
1# Full working Python code
2from collections import defaultdict
3
4def maxPoints(points, s):
5 n = len(points)
6 point_info = [(max(abs(x), abs(y)), s[i]) for i, (x, y) in enumerate(points)]
7 point_info.sort()
8 max_count = 0
9 left = 0
10 tags = defaultdict(int)
11
12 for right in range(n):
13 tags[point_info[right][1]] += 1
14 while tags[point_info[right][1]] > 1:
15 tags[point_info[left][1]] -= 1
16 if tags[point_info[left][1]] == 0:
17 del tags[point_info[left][1]]
18 left += 1
19 max_count = max(max_count, len(tags))
20 return max_count
21
22points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]]
23s = 'abdca'
24print(maxPoints(points, s))ℹ
Complexity note: The sorting step takes O(n log n) time, and we use a hash map to track unique tags, which requires O(n) space.
- 1The maximum distance to include a point is determined by the maximum of its x and y coordinates.
- 2Using a sliding window helps efficiently count unique tags without rechecking all points.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.