Maximum Points Inside the Square Problem
Description
LeetCode Problem 3143.
You are given a 2D array points and a string s where, points[i] represents the coordinates of point i, and s[i] represents the tag of point i.
A valid square is a square centered at the origin (0, 0), has edges parallel to the axes, and does not contain two points with the same tag.
Return the maximum number of points contained in a valid square.
Note:
- A point is considered to be inside the square if it lies on or within the square's boundaries.
- The side length of the square can be zero.
Example 1:

Input: points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"
Output: 2
Explanation:
The square of side length 4 covers two points points[0] and points[1].
Example 2:

Input: points = [[1,1],[-2,-2],[-2,2]], s = "abb"
Output: 1
Explanation:
The square of side length 2 covers one point, which is points[0].
Example 3:
Input: points = [[1,1],[-1,-1],[2,-2]], s = "ccd"
Output: 0
Explanation:
It's impossible to make any valid squares centered at the origin such that it covers only one point among points[0] and points[1].
Constraints:
1 <= s.length, points.length <= 10^5points[i].length == 2-10^9 <= points[i][0], points[i][1] <= 10^9s.length == points.lengthpointsconsists of distinct coordinates.sconsists only of lowercase English letters.
Solution
Approach: Hash Table + Sorting
A point (x, y) is inside the square of half-side d exactly when max(|x|, |y|) <= d, so each point has a single "distance" max(|x|, |y|).
Group the point indices by distance and process the distances from small to large. When a group is added, every tag it contains must be new; if a tag repeats (inside the group or with an earlier one), the square cannot reach this distance and we stop with the count so far. Otherwise add the group size to the answer.
Complexity: time O(n log n), space O(n).
from collections import defaultdict
class Solution:
def maxPointsInsideSquare(self, points: List[List[int]], s: str) -> int:
g = defaultdict(list)
for i, (x, y) in enumerate(points):
g[max(abs(x), abs(y))].append(i)
vis = set()
ans = 0
for d in sorted(g):
idx = g[d]
for i in idx:
if s[i] in vis:
return ans
vis.add(s[i])
ans += len(idx)
return ans