Counting Squares from 2D Integer Coordinates
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are working with points [x, y] located at integer coordinates on the 2D Cartesian plane.
- Stage 1 — Verify four corners (
is_square): Given four 2D integer points, determine whether they form the four corners of a positive-area square. Edges may sit at any angle — tilted squares are valid, not only squares aligned with the coordinate axes. - Stage 2 — Count unique squares in a point cloud (
count_squares, tested by the judge): Given a listpointscontainingNinteger coordinate pairs (which may include duplicate[x, y]entries), return how many distinct positive-area squares have all four of their corners present inpoints.
Follow these counting rules:
- Order independence: Two squares with the exact same set of four corner coordinates represent a single square regardless of vertex ordering.
- Arbitrary orientation: Both axis-parallel and rotated squares count.
- Duplicate coordinates: Multiple copies of the same
[x, y]coordinate represent the same geometric point — duplicates must never form zero-length shapes and must not cause a valid square to be counted multiple times.
Aim to progress past O(n^4) four-corner combinations and O(n^3) three-corner checks to an O(n^2) average-time solution using hash lookups.
Examples
Example 1
Input:
points = [[2, 1], [5, 1], [5, 4], [2, 4]]
Output: 1
Walk-through: All four outer edges have length 3 and both diagonals have squared length 18 (2 * 3^2), forming one axis-aligned square.
Example 2
Input:
points = [[1, 0], [3, 1], [2, 3], [0, 2]]
Output: 1
Walk-through: Stepping along (2, 1), (-1, 2), (-2, -1), and (1, -2) gives four perpendicular edges of squared length 5 and two diagonals of squared length 10, forming one tilted square.
Example 3
Input:
points = [[0, 0], [3, 4], [8, 4], [5, 0]]
Output: 0
Walk-through: Every side has length 5, so the shape is a rhombus, but its diagonals have squared lengths 80 and 20 rather than 50 — the corners are not 90-degree angles, so 0 squares exist.
Example 4
Input:
points = [[0, 0], [2, 0], [4, 0], [0, 2], [2, 2], [4, 2], [1, 1], [1, 3], [0, 2]]
Output: 3
Walk-through: Collapsing the duplicate [0, 2] leaves 8 unique coordinates that form 3 distinct squares:
- Left 2 x 2 square: (0, 0), (2, 0), (2, 2), (0, 2)
- Right 2 x 2 square: (2, 0), (4, 0), (4, 2), (2, 2)
- Tilted diamond: (1, 1), (2, 2), (1, 3), (0, 2)
Constraints
1 <= len(points) <= 2 * 10^4- Each
points[i]is[x, y]where-2^31 <= x, y <= 2^31 - 1. - Duplicate
[x, y]entries may occur inpoints.
Step-by-step walkthrough
Understand the goal and clarify assumptions
We work with 2D points at integer coordinates
(x, y)across two closely connected geometry tasks:- Stage 1 (
is_square): Given 4 points, decide whether they form a non-degenerate square (a real square whose side length is strictly greater than0, so stacked points do not count). - Stage 2 (
count_squares, called by the judge): GivenNpoints, count how many distinct non-degenerate squares have all 4 corners present in the input.
Crucially, squares do not have to line up with the x and y axes — a tilted square at any angle still counts, whereas a stretched rectangle or slanted rhombus does not:
Axis-aligned (Ex 1) Tilted square (Ex 2) Rhombus — NOT a square (Ex 3) (2,4) --- (5,4) (2,3) (3,4) ----- (8,4) | | / \ / / | | (0,2) (3,1) / / (2,1) --- (5,1) \ / (0,0) ----- (5,0) (1,0)Before writing code, let's pin down three clean rules that match all sample tests:
- Duplicate coordinates collapse to a single geometric point. In Example 4,
(0, 2)appears twice in the input list, yet each square using(0, 2)is still counted once (3total). Converting the input into a set of unique(x, y)tuples immediately prevents duplicates from forming zero-area fake squares or inflating counts. - Corner order does not matter. A square is defined purely by the set of its 4 corner positions.
- Stick to integer math. Square roots like
sqrt(5)introduce tiny floating-point rounding errors, so we will use squared distances and integer vector rotations throughout.
- Stage 1 (
Stage 1: validate 4 points using squared distances
Among 4 points, there are
4 * 3 / 2 = 6pairs of points: 4 outer sides and 2 diagonals crossing the middle.If the 4 points form a square of side length
s > 0: - Each of the 4 sides has squared lengths^2. - By the Pythagorean theorem (s^2 + s^2 = 2 * s^2), each of the 2 diagonals has squared length2 * s^2.If we compute
(dx * dx + dy * dy)for all 6 pairs and sort them from smallest to largest, a valid square must produce[a, a, a, a, 2a, 2a]witha > 0:Sorted 6 squared distances for a square of side s (let a = s^2): index: 0 1 2 3 4 5 value: [ a, a, a, a, 2a, 2a ] \_____4 sides____/ \_2 diags_/Why do we check both equal sides and equal diagonals? Because Example 3's rhombus
(0,0), (3,4), (8,4), (5,0)also has 4 equal sides (a = 25), but one diagonal is stretched (80) and the other is squashed (20), giving[20, 25, 25, 25, 25, 80]— which our sorted check cleanly rejects!from typing import List def is_square(four_points: List[List[int]]) -> bool: """Part A: return True if these 4 points form a non-degenerate square.""" # squared_dists: all 6 pairwise squared distances (dx^2 + dy^2) among the 4 points. # Keeping distances squared avoids square roots and floating-point rounding bugs. squared_dists = [] for i in range(4): for j in range(i + 1, 4): dx = four_points[i][0] - four_points[j][0] dy = four_points[i][1] - four_points[j][1] squared_dists.append(dx * dx + dy * dy) # In a valid square of side length s > 0, sorting the 6 squared distances puts # the 4 equal sides (s^2) first and the 2 equal diagonals (2 * s^2) last. squared_dists.sort() side_sq = squared_dists[0] # Reject degenerate shapes where two or more points sit on the exact same spot. if side_sq == 0: return False four_equal_sides = ( squared_dists[0] == squared_dists[1] == squared_dists[2] == squared_dists[3] ) two_equal_diagonals = squared_dists[4] == squared_dists[5] # Checking diag^2 == 2 * side^2 confirms 90-degree corners via the Pythagorean theorem. right_angle_corners = squared_dists[4] == 2 * side_sq return four_equal_sides and two_equal_diagonals and right_angle_cornersStage 2 progression: from O(n^4) to O(n^3)
Now suppose we have
ndistinct points (withNup to20,000). Let's walk through the runtime ladder:- Brute force — O(n^4): Test every combination of 4 distinct points with
is_square. Every square is checked once, so it is guaranteed correct, but20,000points have roughlyn^4 / 24 ≈ 6.7 * 10^15groups of 4 — completely impossible to run in time. - Three-corner check — O(n^3): Notice that 3 corners of a square already lock in where the 4th corner must be! If we store all points in a hash set (a data structure that checks whether a point exists in
O(1)average time), we only need to pick 3 points(p, q, r)that form an equal-length right-angle "L" atp, and check whether the 4th cornerq + r - pis in the set. That eliminates one loop, but20,000^3is still around10^12operations.
Can we lock in a square using only 2 points instead of 3?
- Brute force — O(n^4): Test every combination of 4 distinct points with
Key geometric insight: 2 points on one side fix at most 2 squares
Suppose we pick just two distinct points
p1 = (x1, y1)andp2 = (x2, y2)and treat the segment between them as one side of a candidate square.The arrow (vector) from
p1top2moves right bydx = x2 - x1and up bydy = y2 - y1. To turn an arrow by 90 degrees on a grid, we swap its two steps and flip one sign:- Turning
(dx, dy)by +90 degrees (counterclockwise) gives(-dy, dx). - Turning
(dx, dy)by -90 degrees (clockwise) gives(dy, -dx).
Let's verify this on Example 2! Take
p1 = (1, 0)andp2 = (3, 1), so(dx, dy) = (2, 1)("right 2, up 1"): - Turning +90 degrees gives(-1, 2)("left 1, up 2"). Notice the squared length is(-1)^2 + 2^2 = 5, matching2^2 + 1^2 = 5, and their dot product is2 * (-1) + 1 * 2 = 0(meaning a perfect 90-degree angle!). - Shifting bothp1andp2by(-dy, dx)lands on(0, 2)and(2, 3)— the exact top two corners of Example 2's tilted square! Shifting both by(dy, -dx)lands on(2, -2)and(4, -1), checking the candidate square on the opposite side:left_c3 = (0, 2) -------- left_c4 = (2, 3) \ \ +(-dy,dx) \ Square 1 (+90) \ +(-dy,dx) \ \ p1 = (1, 0) ========= p2 = (3, 1) <-- chosen edge (dx=2, dy=1) \ \ +(dy,-dx) \ Square 2 (-90) \ +(dy,-dx) \ \ right_c3 = (2, -2) ------ right_c4 = (4, -1)Notice why picking a pair as a side is so clean:
x1 - dy,y1 + dx,x1 + dy, andy1 - dxare always exact integers! We simply check if those two target tuples exist in our hash setunique_points— just 4O(1)lookups per pair of points, bringing the total time down to O(n^2).- Turning
Why we divide the total hits by 4
Wait — if we loop over every unordered pair
(p1, p2)withi < j, how many times does one real square get counted?Trace Example 1's square with corners
A=(2,1), B=(5,1), C=(5,4), D=(2,4): - There are6unordered pairs among these 4 corners: 4 sides (AB,BC,CD,DA) and 2 diagonals (AC,BD). - Whenever our loop visits one of the 4 sides (sayAB), one of the two 90-degree turns points inward onto(D, C)(a hit!) and the other points outward onto((2,-2), (5,-2))(a different square adjacent toAB, if those points exist). - What when our loop visits a diagonal likeAC? Then it treatsAC(squared length18) as a side and looks for corners of a larger tilted square of squared side18— it never re-discoversABCD!Therefore, every distinct square in the input contributes exactly 4 hits (one from each of its 4 sides). Integer division
side_matches // 4gives the exact count of distinct squares.Code the O(n^2) square counter
Let's assemble
count_squarescleanly in three short phases: deduplicate into a set, scan alli < jpoint pairs checking both 90-degree rotations, and divideside_matchesby4.from typing import List, Set, Tuple def count_squares(points: List[List[int]]) -> int: """Part B: count distinct non-degenerate squares whose 4 corners are in points.""" # Phase 1: Deduplicate coordinates so repeated inputs cannot create zero-size # "squares" or count the same geometric square multiple times. # unique_points: set of (x, y) tuples for O(1) average corner existence checks. unique_points: Set[Tuple[int, int]] = set() for x, y in points: unique_points.add((x, y)) distinct_pts = list(unique_points) num_pts = len(distinct_pts) if num_pts < 4: return 0 # Phase 2: Treat every unordered pair of distinct points as one candidate SIDE # of a square. Rotating edge vector (dx, dy) by +90 and -90 degrees gives the # exact integer positions where the other two corners would have to sit. side_matches = 0 for i in range(num_pts): x1, y1 = distinct_pts[i] for j in range(i + 1, num_pts): x2, y2 = distinct_pts[j] dx = x2 - x1 dy = y2 - y1 # Rotate (dx, dy) by +90 degrees -> (-dy, dx): candidate square on the left side. left_c3 = (x1 - dy, y1 + dx) left_c4 = (x2 - dy, y2 + dx) if left_c3 in unique_points and left_c4 in unique_points: side_matches += 1 # Rotate (dx, dy) by -90 degrees -> (dy, -dx): candidate square on the right side. right_c3 = (x1 + dy, y1 - dx) right_c4 = (x2 + dy, y2 - dx) if right_c3 in unique_points and right_c4 in unique_points: side_matches += 1 # Phase 3: Every valid square has 4 sides, and our i < j loop visits each side # once, so each distinct square was counted exactly 4 times. return side_matches // 4Trace Example 4 step by step
In Example 4, the 9 input entries collapse
(0, 2)into 8 unique coordinates forming two2 x 2squares sharing edge(2, 0)-(2, 2)plus one tilted diamond perched across(0, 2)and(2, 2):(1,3) / \ (0,2) -------- (2,2) --- (4,2) | \ / || | | (1,1) || Sq R | | Sq L || | (0,0) -------- (2,0) --- (4,0)Out of
8 * 7 / 2 = 28unordered point pairs: - 3 outer edges ofSq L((0,0)-(2,0),(0,0)-(0,2),(0,2)-(2,2)): each matchesSq Lon one side and misses outside ->+3hits. - 3 outer edges ofSq R((2,0)-(4,0),(4,0)-(4,2),(2,2)-(4,2)): each matchesSq Ron one side and misses outside ->+3hits. - 1 shared vertical edge(2,0)-(2,2)with(dx, dy) = (0, 2): -+90 degshift(-2, 0)checks(0,0)and(0,2)-> hitsSq L(+1)! --90 degshift(2, 0)checks(4,0)and(4,2)-> hitsSq R(+1)! - 4 tilted edges of the diamond ((1,1)-(2,2),(2,2)-(1,3),(1,3)-(0,2),(0,2)-(1,1)): each matches the inward diamond once and misses outward ->+4hits. - All 17 remaining pairs (diagonals and long spans): miss at least one rotated corner ->0hits.Total
side_matches = 3 + 3 + 2 + 4 = 12, and12 // 4 = 3distinct squares.Complete solution
We include both
is_square(for Stage 1) andcount_squares(called by the automated judge for Stage 2).from typing import Any, Dict, List, Optional, Set, Tuple def is_square(four_points: List[List[int]]) -> bool: """Part A: return True if these 4 points form a non-degenerate square.""" # squared_dists: all 6 pairwise squared distances (dx^2 + dy^2) among the 4 points. # Keeping distances squared avoids square roots and floating-point rounding bugs. squared_dists = [] for i in range(4): for j in range(i + 1, 4): dx = four_points[i][0] - four_points[j][0] dy = four_points[i][1] - four_points[j][1] squared_dists.append(dx * dx + dy * dy) # In a valid square of side length s > 0, sorting the 6 squared distances puts # the 4 equal sides (s^2) first and the 2 equal diagonals (2 * s^2) last. squared_dists.sort() side_sq = squared_dists[0] # Reject degenerate shapes where two or more points sit on the exact same spot. if side_sq == 0: return False four_equal_sides = ( squared_dists[0] == squared_dists[1] == squared_dists[2] == squared_dists[3] ) two_equal_diagonals = squared_dists[4] == squared_dists[5] # Checking diag^2 == 2 * side^2 confirms 90-degree corners via the Pythagorean theorem. right_angle_corners = squared_dists[4] == 2 * side_sq return four_equal_sides and two_equal_diagonals and right_angle_corners def count_squares(points: List[List[int]]) -> int: """Part B: count distinct non-degenerate squares whose 4 corners are in points.""" # Phase 1: Deduplicate coordinates so repeated inputs cannot create zero-size # "squares" or count the same geometric square multiple times. # unique_points: set of (x, y) tuples for O(1) average corner existence checks. unique_points: Set[Tuple[int, int]] = set() for x, y in points: unique_points.add((x, y)) distinct_pts = list(unique_points) num_pts = len(distinct_pts) if num_pts < 4: return 0 # Phase 2: Treat every unordered pair of distinct points as one candidate SIDE # of a square. Rotating edge vector (dx, dy) by +90 and -90 degrees gives the # exact integer positions where the other two corners would have to sit. side_matches = 0 for i in range(num_pts): x1, y1 = distinct_pts[i] for j in range(i + 1, num_pts): x2, y2 = distinct_pts[j] dx = x2 - x1 dy = y2 - y1 # Rotate (dx, dy) by +90 degrees -> (-dy, dx): candidate square on the left side. left_c3 = (x1 - dy, y1 + dx) left_c4 = (x2 - dy, y2 + dx) if left_c3 in unique_points and left_c4 in unique_points: side_matches += 1 # Rotate (dx, dy) by -90 degrees -> (dy, -dx): candidate square on the right side. right_c3 = (x1 + dy, y1 - dx) right_c4 = (x2 + dy, y2 - dx) if right_c3 in unique_points and right_c4 in unique_points: side_matches += 1 # Phase 3: Every valid square has 4 sides, and our i < j loop visits each side # once, so each distinct square was counted exactly 4 times. return side_matches // 4✅ Submit now — all tests should pass.
Intuition & how it works
Imagine building square picture frames on a pegboard. As soon as you lay one wooden side between any two pegs p1 and p2, the length and tilt of the entire square are already locked in: the frame can only flip onto the left side of that stick or onto the right side of that stick. That means two pegs completely determine the exact coordinates where the other two pegs would need to be, and we can simply glance at those two spots to see if pegs are there.
The obvious brute-force approach checks every group of 4 points (O(n^4) time), or every group of 3 points (O(n^3) time), which requires trillions of checks when N = 20,000. Another common trap is grouping points by matching x and y coordinates, which completely misses rotated (tilted) squares. By storing all unique points in a hash set (a collection that answers "is (x, y) present?" in O(1) average constant time) and rotating each pair's vector (dx, dy) by 90 degrees into perpendicular vectors (-dy, dx) and (dy, -dx) (vectors at a right angle of equal length), we check every possible orientation using pure integer arithmetic in O(n^2) time.
Let's trace Example 2's tilted square of 4 points: [(1, 0), (3, 1), (2, 3), (0, 2)].
1. All 4 points are unique. Take the pair p1 = (1, 0) and p2 = (3, 1), which gives edge vector (dx, dy) = (2, 1).
2. Rotating (2, 1) by +90 degrees gives (-dy, dx) = (-1, 2), asking for (0, 2) and (2, 3) — both are in the set (+1 hit)!
3. Rotating (2, 1) by -90 degrees gives (dy, -dx) = (1, -2), asking for (2, -2) and (4, -1) — not in the set.
4. Across all 6 pairs, each of the 4 tilted sides finds this square once (while the 2 diagonals (1, 0)-(2, 3) and (3, 1)-(0, 2) look for larger squares of squared side 10 and miss), giving 4 hits and 4 // 4 = 1 square.
Complexity
- Stage 1 (
is_square) time and space —O(1): There are always 4 points and4 * 3 / 2 = 6pairwise squared distances, so computing and sorting 6 numbers takes a tiny fixed number of steps and constant memory. - Stage 2 (
count_squares) time —O(N + n^2)on average (whereNis the input length andn <= Nis the number of unique points): InsertingNpoints into the hash set takesO(N)average time. Then we loop overn * (n - 1) / 2unordered pairs of unique points, performing 4O(1)average hash-set lookups per pair. - Stage 2 (
count_squares) space —O(n): We store each unique(x, y)coordinate once inunique_pointsand once indistinct_pts. - Why
O(n^2)is hard to beat when listing squares: A densek x kgrid ofn = k^2integer points already contains roughlyn^2 / 12distinct squares (including tilted ones), so any algorithm that discovers squares one by one must spend at leastOmega(n^2)time in the worst case.
Edge cases
- Fewer than 4 distinct points: Even if
pointshas 100 entries that are all duplicates of 3 coordinates,len(distinct_pts) < 4returns0immediately. - Degenerate zero-length "squares": A non-degenerate square is a square with positive side length (
s > 0). Deduplicating coordinates incount_squares(and checkingside_sq == 0inis_square) ensures[[3, 3], [3, 3], [3, 3], [3, 3]]returns0/False. - Tilted squares at arbitrary angles (like Example 2): Because
(-dy, dx)and(dy, -dx)work for any integer step(dx, dy)— such as(2, 1)— squares tilted at any angle are found without trigonometry. - Rhombuses (equal sides without 90-degree angles): A rhombus is a four-sided shape with 4 equal sides whose corners do not have to be 90 degrees, like Example 3
(0,0), (3,4), (8,4), (5,0).is_squarerejects it via the diagonal checkdiag^2 == 2 * side^2, andcount_squaresnever matches it because a 90-degree turn from(3, 4)misses(8, 4)and(5, 0). - Squares sharing an edge (like Example 4): If two squares sit side by side sharing an edge, one 90-degree turn matches the left square and the opposite 90-degree turn matches the right square, so both still get counted accurately.
- 32-bit integer extremes: Python integers grow automatically without overflowing. In C++ or Java,
x1 - dycan reach roughly3 * 2^31(requiring 64-bitint64_t/long), and inis_squaredx^2 + dy^2can reach2^65(overflowing even 64-bit integers unless you use 128-bit integers or check 90-degree vector rotations instead of squared distances).
Common mistakes
- Checking only 4 equal sides in
is_square: Any non-square rhombus has 4 equal sides! You must also check that the two diagonals are equal and satisfydiag^2 == 2 * side^2. - Using
math.sqrtand floating-point comparisons:math.sqrt(5)cannot be represented with complete accuracy in binary floating-point, risking subtle rounding failures when exact integer squared distances work cleanly. - Forgetting to deduplicate input points before pairing: Keeping duplicate points creates pairs with
dx = 0, dy = 0(counting single repeated points as squares) and multiplies the count of real squares. - Dividing by the wrong symmetry factor: With unordered pairs (
i < j) and both+90and-90turns tested as sides, every square is found4times (// 4). Using ordered pairs (i != j) finds each square8times (// 8); using pairs as diagonals finds each square2times (// 2). - Using floating-point division when treating pairs as diagonals: The midpoint of two integer points can end in
.5, and rounding or float arithmetic can produce false hits unless you check integer parity (whether an integer is even or odd).
Alternative approaches
- Treat each pair of points as a diagonal instead of a side: Given opposite corners
(x1, y1)and(x3, y3), the center of the square is((x1 + x3) / 2, (y1 + y3) / 2)and the half-diagonal vector is((x3 - x1) / 2, (y3 - y1) / 2). Rotating the half-diagonal by 90 degrees around the center gives the other two corners, doubled to stay in integers, as(x1 + x3 - (y3 - y1), y1 + y3 + (x3 - x1))and(x1 + x3 + (y3 - y1), y1 + y3 - (x3 - x1)). If those doubled sums are odd, the true corners lie at.5half-integer coordinates and cannot be in our integer set, so we skip the pair; otherwise we divide by2, look up both corners inunique_points, and divide the final count by2(since each square has 2 diagonals). This cuts hash lookups in half compared to the side method, at the cost of slightly trickier midpoint algebra.
Follow-up questions
- What if duplicate points in the input represent separate selectable items, so we want the number of 4-index combinations that form squares? Replace the
unique_pointsset with a frequency dictionaryfreq[(x, y)]counting how many times each coordinate appears. Still loop only over pairs of distinct coordinatesp1andp2so zero-size shapes remain excluded, and whenever a square with corners(p1, p2, p3, p4)is found, addfreq[p1] * freq[p2] * freq[p3] * freq[p4]tototalbefore dividing by4at the end. - What if points arrive one at a time in a stream and you must report the updated square count after each arrival? Maintain
unique_pointsand a runningtotal. When a brand-new pointparrives (ignore it ifpis already inunique_points), pairpwith every existing pointqand test both 90-degree turns of sidep-q; because every newly completed square touchespalong two of its sides, addnew_hits // 2tototalinO(n)time per insertion. - How would you optimize further if only axis-aligned squares (sides parallel to the x and y axes) were counted? Treat each pair
(x1, y1)and(x2, y2)as an opposite diagonal: it can form an axis-aligned square if and only ifx1 != x2andabs(x2 - x1) == abs(y2 - y1), in which case the other two corners must be(x1, y2)and(x2, y1). Even better, group points byx-coordinate into columns and split columns into "light" (<= sqrt(n)points, where you pair points within the column) and "heavy" (> sqrt(n)points, where you pair heavy columns against each other), reducing worst-case time fromO(n^2)toO(n * sqrt(n)).
Follow-up questions
- What if duplicate points in the input represent separate selectable items, so we want the number of 4-index combinations that form squares?
- What if points arrive one at a time in a stream and you must report the updated square count after each arrival?
- How would you optimize further if only axis-aligned squares (sides parallel to the x and y axes) were counted?
Similar questions
- Square Submatrices Filled with Ones
- Thread-Safe In-Memory Event Bus
- Thread-Safe One-Shot Latch
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
More Purestorage interview questions
- Square Submatrices Filled with Ones Medium
- Thread-Safe In-Memory Event Bus Medium
- Thread-Safe One-Shot Latch Medium Pro