Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
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 <= 105points[i].length == 2-109 <= points[i][0], points[i][1] <= 109s.length == points.lengthpoints consists of distinct coordinates.s consists only of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Binary Search
[[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]] "abdca"
[[1,1],[-2,-2],[-2,2]] "abb"
[[1,1],[-1,-1],[2,-2]] "ccd"
maximize-the-distance-between-points-on-a-square)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3143: Maximum Points Inside the Square
class Solution {
public int maxPointsInsideSquare(int[][] points, String s) {
TreeMap<Integer, List<Integer>> g = new TreeMap<>();
for (int i = 0; i < points.length; ++i) {
int x = points[i][0], y = points[i][1];
int key = Math.max(Math.abs(x), Math.abs(y));
g.computeIfAbsent(key, k -> new ArrayList<>()).add(i);
}
boolean[] vis = new boolean[26];
int ans = 0;
for (var idx : g.values()) {
for (int i : idx) {
int j = s.charAt(i) - 'a';
if (vis[j]) {
return ans;
}
vis[j] = true;
}
ans += idx.size();
}
return ans;
}
}
// Accepted solution for LeetCode #3143: Maximum Points Inside the Square
func maxPointsInsideSquare(points [][]int, s string) (ans int) {
g := map[int][]int{}
for i, p := range points {
key := max(p[0], -p[0], p[1], -p[1])
g[key] = append(g[key], i)
}
vis := [26]bool{}
keys := []int{}
for k := range g {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
idx := g[k]
for _, i := range idx {
j := s[i] - 'a'
if vis[j] {
return
}
vis[j] = true
}
ans += len(idx)
}
return
}
# Accepted solution for LeetCode #3143: Maximum Points Inside the Square
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
// Accepted solution for LeetCode #3143: Maximum Points Inside the Square
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3143: Maximum Points Inside the Square
// class Solution {
// public int maxPointsInsideSquare(int[][] points, String s) {
// TreeMap<Integer, List<Integer>> g = new TreeMap<>();
// for (int i = 0; i < points.length; ++i) {
// int x = points[i][0], y = points[i][1];
// int key = Math.max(Math.abs(x), Math.abs(y));
// g.computeIfAbsent(key, k -> new ArrayList<>()).add(i);
// }
// boolean[] vis = new boolean[26];
// int ans = 0;
// for (var idx : g.values()) {
// for (int i : idx) {
// int j = s.charAt(i) - 'a';
// if (vis[j]) {
// return ans;
// }
// vis[j] = true;
// }
// ans += idx.size();
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3143: Maximum Points Inside the Square
function maxPointsInsideSquare(points: number[][], s: string): number {
const n = points.length;
const g: Map<number, number[]> = new Map();
for (let i = 0; i < n; ++i) {
const [x, y] = points[i];
const key = Math.max(Math.abs(x), Math.abs(y));
if (!g.has(key)) {
g.set(key, []);
}
g.get(key)!.push(i);
}
const keys = Array.from(g.keys()).sort((a, b) => a - b);
const vis: boolean[] = Array(26).fill(false);
let ans = 0;
for (const key of keys) {
const idx = g.get(key)!;
for (const i of idx) {
const j = s.charCodeAt(i) - 'a'.charCodeAt(0);
if (vis[j]) {
return ans;
}
vis[j] = true;
}
ans += idx.length;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.