Square Count Over 2D Coordinates
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement the function
def count_squares(points: List[Tuple[int, int]]) -> int:
Given a list points of 2D integer coordinates (x, y), compute how many distinct geometric squares can be formed by choosing four vertices from points.
Squares may lie at any angle in the plane — horizontal/vertical alignment is not required. Every valid square must have positive area (four distinct corner locations), and repeated coordinate pairs in points represent the same location in the plane rather than separate corners.
Examples
Example 1
Input: points = [(-1, 0), (1, 0), (0, 1), (0, -1), (-1, 2), (1, 2)]
Output: 2
Walk-through:
- {(-1, 0), (1, 0), (1, 2), (-1, 2)} forms a 2 x 2 square aligned with the coordinate axes.
- {(-1, 0), (1, 0), (0, 1), (0, -1)} shares the bottom two points and forms a second square rotated by 45 degrees with side length sqrt(2).
Example 2
Input: points = [(1, 0), (4, 1), (3, 4), (0, 3)]
Output: 1
Walk-through:
- Consecutive edge vectors are (3, 1), (-1, 3), (-3, -1), and (1, -3): all four sides have length sqrt(10) and adjacent sides meet at 90 degrees (3 * (-1) + 1 * 3 = 0), yielding one tilted square.
Constraints
0 <= len(points) <= 500-1000 <= x, y <= 1000for every(x, y)inpoints(all coordinates are integers)- A valid square requires four distinct coordinate locations.
Step-by-step walkthrough
Understand the input, tilted squares, and duplicates
We are given up to
n = 500integer coordinates(x, y)in[-1000, 1000]and asked how many distinct squares have all four corners in the set. Keep three important rules in mind:- Any rotation is valid: Squares do not have to align with the x/y axes or sit at 45 degrees. For example,
(0, 0), (2, 1), (1, 3), (-1, 2)is a valid tilted square whose side vector is(2, 1). - Four distinct points: If the input repeats
(0, 0)twice, both entries refer to the same geometric point in the plane, so we must deduplicate first. - Lists versus tuples: Automated judges sometimes pass coordinates as 2-element
lists like[0, 0], which cannot be placed in a Pythonsetdirectly until converted to(x, y)tuples.
- Any rotation is valid: Squares do not have to align with the x/y axes or sit at 45 degrees. For example,
Why checking every 4-point subset is too slow
A literal brute-force solution chooses every 4-point combination
(A, B, C, D)and checks whether their 6 pairwise squared distances sort to[s, s, s, s, 2s, 2s]withs > 0.At
n = 500, the number of 4-point subsets is500 * 499 * 498 * 497 / 24, which is roughly 2.6 billion groups — far too slow (O(n^4)).To drop from
O(n^4)toO(n^2), we store all distinct points in a hash set (a hash-table collection supportingO(1)average membership checks). If picking just 2 points uniquely determines where the other 2 corners must sit, we only have500 * 499 / 2 = 124,750pairs to inspect!Key geometry: one diagonal fixes the other two corners
In any square, the two diagonals have equal length, cross at their exact midpoint
M, and meet at a 90-degree right angle. That means once we pick two distinct pointsA = (ax, ay)andC = (cx, cy)as opposite corners, the entire square is locked in place:B = M + (-hy, hx) * / \ / \ h = C - M = (hx, hy) / M \ 90-deg counterclockwise rotation of h = (-hy, hx) A *-----+-----* C \ / 90-deg clockwise rotation of h = ( hy, -hx) \ / \ / * D = M + (hy, -hx)Let's write out the exact algebra step by step without skipping anything: 1. Midpoint
M:Mx = (ax + cx) / 2,My = (ay + cy) / 22. Half-diagonal vectorh = C - M(usingdx = cx - axanddy = cy - ay):hx = (cx - ax) / 2 = dx / 2,hy = (cy - ay) / 2 = dy / 23. Rotatehby +90 and -90 degrees (in 2D, rotating(u, v)by 90 degrees swaps the components and negates one, giving(-v, u)and(v, -u)): -B = (Mx - hy, My + hx) = ((ax + cx - dy) / 2, (ay + cy + dx) / 2)-D = (Mx + hy, My - hx) = ((ax + cx + dy) / 2, (ay + cy - dx) / 2)Notice also that since
A != C,(dx, dy)is non-zero, soBandDare guaranteed to be distinct fromA,C, and each other!Stay in exact integers with an evenness check
Suppose
A = (0, 1)andC = (2, 2). Plugging into our formulas givesB = (0.5, 2.5)andD = (1.5, 0.5). Since every input point has integer coordinates, no input point can ever sit at(0.5, 2.5)or(1.5, 0.5)!Be careful: if we blindly used integer floor division
// 2without checking evenness first,twice_bx = 0 + 2 - 1 = 1and1 // 2would silently round0.5down to0, snapping a half-integer corner onto a real grid point and inventing fake squares!Instead, we compute the doubled coordinates (
twice_bx,twice_by,twice_dx,twice_dy) as exact integers and verify all four are even (% 2 == 0) before dividing by2:def diagonal_other_corners( a: Tuple[int, int], c: Tuple[int, int] ) -> Optional[Tuple[Tuple[int, int], Tuple[int, int]]]: """Return the other two corners (b, d) for diagonal a-c, or None if non-integer.""" ax, ay = a cx, cy = c sum_x = ax + cx sum_y = ay + cy dx = cx - ax dy = cy - ay # Work in doubled coordinates first so we never touch floating-point numbers. twice_bx = sum_x - dy twice_by = sum_y + dx twice_dx = sum_x + dy twice_dy = sum_y - dx # Input points are integers, so half-integer corners can never exist in `point_set`. # Checking `% 2 != 0` before `// 2` prevents floor division from rounding onto nearby points. if ( twice_bx % 2 != 0 or twice_by % 2 != 0 or twice_dx % 2 != 0 or twice_dy % 2 != 0 ): return None corner_b = (twice_bx // 2, twice_by // 2) corner_d = (twice_dx // 2, twice_dy // 2) return corner_b, corner_d(Fun math bonus: expanding
sum_x - dy = ax + cx - cy + ayshows all four numerators actually share the exact same even/odd parity asax + ay + cx + cy, though checking all four explicitly makes the code completely self-evident.)Deduplicate and convert points to hashable tuples
Before running the pair loop, we pass
pointsthrough a small helper that turns each[x, y]or(x, y)into a hashable(x, y)tuple and drops duplicates:def unique_points(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """Convert points (lists or tuples) into distinct hashable (x, y) tuples.""" seen: Set[Tuple[int, int]] = set() distinct: List[Tuple[int, int]] = [] for p in points: coord = (p[0], p[1]) if coord not in seen: seen.add(coord) distinct.append(coord) return distinctAvoid double-counting: two diagonals per square
When we loop over unordered pairs
0 <= i < j < len(pts), how many times is a valid square{A, B, C, D}counted?A *-------* B Pair (A, C): treats A-C as diagonal -> finds B and D in point_set (+1) | \ / | Pair (B, D): treats B-D as diagonal -> finds A and C in point_set (+1) | X | Pair (A, B): treats A-B as diagonal -> checks smaller diamond corners | / \ | (0.5, 0.5) and (0.5, -0.5), NOT {A, B, C, D}! D *-------* CEvery real square has 2 diagonals (
A-CandB-D), so our unordered pair loop incrementsdiagonal_matchestwice per square. Dividing by 2 (diagonal_matches // 2) gives the exact count of distinct squares!Trace Example 2 step by step
Let's trace
points = [(1, 0), (4, 1), (3, 4), (0, 3)](a tilted square with side vector(3, 1)):point_set = {(1, 0), (4, 1), (3, 4), (0, 3)} 1. Pair (1, 0) & (4, 1): sum=(5, 1), d=( 3, 1) -> corners (2, 2) & (3, -1) -> missing 2. Pair (1, 0) & (3, 4): sum=(4, 4), d=( 2, 4) -> corners (0, 3) & (4, 1) -> BOTH IN SET! (matches = 1) 3. Pair (1, 0) & (0, 3): sum=(1, 3), d=(-1, 3) -> corners (-1,1) & (2, 2) -> missing 4. Pair (4, 1) & (3, 4): sum=(7, 5), d=(-1, 3) -> corners (2, 2) & (5, 3) -> missing 5. Pair (4, 1) & (0, 3): sum=(4, 4), d=(-4, 2) -> corners (1, 0) & (3, 4) -> BOTH IN SET! (matches = 2) 6. Pair (3, 4) & (0, 3): sum=(3, 7), d=(-3,-1) -> corners (2, 2) & (1, 5) -> missing Result: diagonal_matches // 2 = 2 // 2 = 1Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def unique_points(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """Convert points (lists or tuples) into distinct hashable (x, y) tuples.""" seen: Set[Tuple[int, int]] = set() distinct: List[Tuple[int, int]] = [] for p in points: coord = (p[0], p[1]) if coord not in seen: seen.add(coord) distinct.append(coord) return distinct def diagonal_other_corners( a: Tuple[int, int], c: Tuple[int, int] ) -> Optional[Tuple[Tuple[int, int], Tuple[int, int]]]: """Return the other two corners (b, d) for diagonal a-c, or None if non-integer.""" ax, ay = a cx, cy = c # Center M is ((ax + cx) / 2, (ay + cy) / 2); half-diagonal h is ((cx - ax) / 2, (cy - ay) / 2). # Rotating h by +/-90 degrees gives (-dy / 2, dx / 2) and (dy / 2, -dx / 2). sum_x = ax + cx sum_y = ay + cy dx = cx - ax dy = cy - ay # Work in doubled coordinates first so we never touch floating-point numbers. twice_bx = sum_x - dy twice_by = sum_y + dx twice_dx = sum_x + dy twice_dy = sum_y - dx # Input points are integers, so half-integer corners can never exist in `point_set`. # Checking `% 2 != 0` before `// 2` prevents floor division from rounding onto nearby points. if ( twice_bx % 2 != 0 or twice_by % 2 != 0 or twice_dx % 2 != 0 or twice_dy % 2 != 0 ): return None corner_b = (twice_bx // 2, twice_by // 2) corner_d = (twice_dx // 2, twice_dy // 2) return corner_b, corner_d def count_squares(points: List[Tuple[int, int]]) -> int: # Deduplicate first so repeated input coordinates cannot inflate the square count. pts = unique_points(points) # point_set: hash set of distinct (x, y) tuples for O(1) average corner lookups point_set = set(pts) diagonal_matches = 0 num_pts = len(pts) # Check every unordered pair (pts[i], pts[j]) as a candidate diagonal of a square. for i in range(num_pts): for j in range(i + 1, num_pts): corners = diagonal_other_corners(pts[i], pts[j]) if corners is None: continue corner_b, corner_d = corners if corner_b in point_set and corner_d in point_set: diagonal_matches += 1 # Every valid square has two diagonals (a-c and b-d), so each square is counted twice. return diagonal_matches // 2✅ Submit now — all tests should pass.
Intuition & how it works
Imagine pinning two opposite corners A and C of a rigid paper square onto a pegboard: once those two opposite pins are in place, the square cannot slide, stretch, or spin anymore! Its center M sits halfway between A and C, and the other two corners B and D sit the exact same half-diagonal distance away from M, rotated by 90 degrees. By storing all input points in a hash set (an unordered collection backed by a hash table that answers "is this coordinate present?" in O(1) average time), we can test any pair of points (A, C) as a candidate diagonal and look up whether its required partner corners B and D both exist. Every complete square has two diagonals (A-C and B-D), so dividing total diagonal hits by 2 counts each square once.
Why do the naive approaches fail? Checking every 4-point group directly takes O(n^4) time — roughly 2.6 billion subsets when n = 500. On the other hand, assuming corners look like (ax, cy) and (cx, ay) only detects axis-aligned squares (whose edges run horizontally and vertically) and misses every rotated square, such as a 45-degree diamond or a tilted square with slope 1/2.
Let's trace Example 2 ([(1, 0), (4, 1), (3, 4), (0, 3)]) when the loop tests opposite corners A = (1, 0) and C = (3, 4):
A = (1, 0), C = (3, 4) -> sum = (4, 4), (dx, dy) = (2, 4)
Doubled corners:
twice_b = (4 - 4, 4 + 2) = (0, 6) (all even!) -> B = (0, 3) in point_set!
twice_d = (4 + 4, 4 - 2) = (8, 2) (all even!) -> D = (4, 1) in point_set!
Later, pair (4, 1) & (0, 3) is the other diagonal and finds (1, 0) & (3, 4).
None of the 4 side pairs find both partner corners in point_set.
Total count = 2 // 2 = 1 square.
Complexity
Let n be the number of input points (m <= n distinct points after deduplication).
- Time:
O(n^2)average. Deduplicating and buildingpoint_setscans thenpoints once inO(n)average time. The nested loop then inspectsm * (m - 1) / 2unordered pairs, doing constant integer arithmetic and at most twoO(1)average hash-set lookups per pair. - Space:
O(n). Bothptsandpoint_setstore at mostncoordinate tuples.
Edge cases
- Fewer than 4 distinct points (including
[]): Either the nested loop runs zero times orpoint_setcannot contain two additional distinct corners, returning0. - Duplicate coordinates in the input:
unique_pointscollapses repeated coordinates like[(0, 0), (0, 0), ...]into a single point so a unit square is never counted multiple times. - Arbitrary tilt angles: Squares tilted at slopes like
(2, 1)or(3, 2)are detected cleanly alongside axis-aligned and 45-degree squares. - Non-square quadrilaterals: Rectangles (equal diagonals that are not perpendicular) and rhombuses (perpendicular diagonals of unequal length) fail the 90-degree equal-half-diagonal check and return
0. - Half-integer candidate corners: Pairs like
(0, 1)and(2, 2)produce odd doubled coordinates (twice_bx = 1) and returnNoneimmediately rather than rounding onto an integer point. - Negative coordinates: In Python,
% 2always evaluates to0or1even for negative integers (-3 % 2 == 1), and// 2divides negative even integers exact-halves (-2 // 2 == -1).
Common mistakes
- Using
// 2,int(...), orround(...)without checking% 2 != 0first: Floor-dividing an odd numerator snaps a half-integer coordinate like(1.5, 0.5)onto(1, 0), which may happen to be inpoint_setand report phantom squares (for instance on[(2, 2), (2, 0), (0, 1), (1, 0), (0, 2)]). - Forgetting
// 2(or dividing by the wrong symmetry factor): Unordered pairs(i < j)visit each square's two diagonals once each (// 2); ordered pairs(i != j)visit each square four times (// 4). - Inserting raw input items into
set(points): When the judge passes points as[x, y]lists instead of(x, y)tuples,set(points)crashes withTypeError: unhashable type: 'list'. - Only checking
(ax, cy)and(cx, ay): That formula only works when the diagonal lies at 45 degrees (an axis-aligned square) and misses rotated squares.
Alternative approaches
- Treat each pair as a square's side (
O(n^2)time): Given two distinct pointsAandBforming side vector(dx, dy) = (bx - ax, by - ay), rotating(dx, dy)by+90degrees ((-dy, dx)) gives candidate cornersA + (-dy, dx)andB + (-dy, dx)on one side of segmentAB(no division by 2 or parity check needed!). Checking unordered pairs with both+90and-90rotations finds each square once from each of its 4 sides, so you divide by4at the end. - Brute-force 4-point distance signature (
O(n^4)time): Check every 4-tuple of distinct points by sorting their 6 pairwise squared Euclidean distances and testingd[0] > 0andd == [s, s, s, s, 2*s, 2*s]. Far too slow forn = 500, effortless as an automated test oracle forn <= 10.
Follow-up questions
- Does expanding the coordinate bounds to huge integers affect your runtime or require arithmetic changes? The solution runs in
O(n^2)average time andO(n)space regardless of coordinate magnitude because hash-set lookups depend on point countn, not coordinate span! For huge coordinates (say10^12), our exact integer parity check avoids IEEE-754 float precision loss (which degrades above2^53); in fixed-width languages like C++ or Java, use 64-bitlongintegers sinceax + cx - dycan reach4 * max_coord. (Note that on a densem x mgrid ofn = m^2points there aren * (n - 1) / 12squares, so any algorithm that inspects each square individually cannot beatO(n^2)in the worst case.) - How could you simplify the geometry if valid squares had to have horizontal and vertical sides? An axis-aligned square's diagonal
(ax, ay) -> (cx, cy)must have non-zero equal horizontal and vertical spans (ax != cxandabs(cx - ax) == abs(cy - ay)), and its other two corners are simply(ax, cy)and(cx, ay)with no rotation math needed. You can also speed up sparse inputs by groupingycoordinates perxcolumn (cols[x]) and only pairing points that share the samexcoordinate or the samex - ydiagonal, while worst-case time remainsO(n^2). - What changes are needed to output each distinct square's four vertices rather than just the total? Whenever both
corner_bandcorner_dexist inpoint_set, canonicalize the four corners by sorting them intosquare = tuple(sorted([pts[i], pts[j], corner_b, corner_d]))and insertsquareinto afound_squaresset. Because both diagonals of the same square produce the exact same sorted 4-tuple, the set automatically deduplicates them, and you can returnlist(found_squares)(orsorted(found_squares)).
Follow-up questions
- Does expanding the coordinate bounds to huge integers affect your runtime or require arithmetic changes?
- How could you simplify the geometry if valid squares had to have horizontal and vertical sides?
- What changes are needed to output each distinct square's four vertices rather than just the total?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array