Maximum Points Inside the Square - Problem

You are given a 2D array points where points[i] represents the coordinates of point i, and a string s where s[i] represents the tag of point i.

A valid square is a square that:

  • Is centered at the origin (0, 0)
  • Has edges parallel to the axes
  • 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.

Input & Output

Example 1 — Basic Case
$ Input: points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"
Output: 2
💡 Note: The square with maximum side length that doesn't contain duplicate tags has size 4 (distance 2 from origin), containing points [2,2] (tag 'a') and [-1,-2] (tag 'b'). Total: 2 points.
Example 2 — All Different Tags
$ Input: points = [[1,1],[-2,-2],[3,-1]], s = "abb"
Output: 1
💡 Note: The largest valid square can only contain 1 point because tags 'b' appear twice. The square of size 2 (distance 1) contains only [1,1] with tag 'a'.
Example 3 — Single Point
$ Input: points = [[1,1]], s = "a"
Output: 1
💡 Note: Only one point exists, so the maximum is 1.

Constraints

  • 1 ≤ points.length ≤ 105
  • points[i].length == 2
  • -109 ≤ points[i][0], points[i][1] ≤ 109
  • s.length == points.length
  • s consists of lowercase English letters

Visualization

Tap to expand
Maximum Points Inside the Square INPUT (0,0) a b d c a points = [[2,2],[-1,-2], [-4,4],[-3,1],[3,-3]] s = "abdca" Note: Two points have tag 'a' (shown in red circles) Scale: 1 unit = ~20px Grid range: -4 to 4 ALGORITHM STEPS 1 Calculate Distance For each point, find max(|x|,|y|) This is min half-side to include it 2 Sort by Distance Process points closest to origin first 3 Check Duplicates Track tags seen at each dist. Stop if duplicate tag found 4 Count Valid Points Return count before conflict Distance Calculation Point Tag max(|x|,|y|) (2,2) 'a' 2 (-1,-2) 'b' 2 (-4,4) 'd' 4 (-3,1) 'c' 3 ( 3,-3) 'a' 3 CONFLICT! FINAL RESULT a b c a (0,0) Inside (valid) Outside/Conflict Output: 2 Max square with side=4 contains points 'a' and 'b' OK - no duplicates! Key Insight: A square centered at origin with half-side length d contains point (x,y) iff max(|x|,|y|) <= d. Sort points by this distance, then greedily expand square until a duplicate tag is encountered. TutorialsPoint - Maximum Points Inside the Square | Optimal Solution
Asked in
Google 12 Amazon 8 Microsoft 6
3.4K Views
Medium Frequency
~25 min Avg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen