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.

  1. 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.
  2. Stage 2 — Count unique squares in a point cloud (count_squares, tested by the judge): Given a list points containing N integer coordinate pairs (which may include duplicate [x, y] entries), return how many distinct positive-area squares have all four of their corners present in points.

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 in points.

Step-by-step walkthrough

  1. 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 than 0, so stacked points do not count).
    • Stage 2 (count_squares, called by the judge): Given N points, 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:

    1. 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 (3 total). Converting the input into a set of unique (x, y) tuples immediately prevents duplicates from forming zero-area fake squares or inflating counts.
    2. Corner order does not matter. A square is defined purely by the set of its 4 corner positions.
    3. 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.
  2. Stage 1: validate 4 points using squared distances

    Among 4 points, there are 4 * 3 / 2 = 6 pairs 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 length s^2. - By the Pythagorean theorem (s^2 + s^2 = 2 * s^2), each of the 2 diagonals has squared length 2 * 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] with a > 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_corners
    
  3. Stage 2 progression: from O(n^4) to O(n^3)

    Now suppose we have n distinct points (with N up to 20,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, but 20,000 points have roughly n^4 / 24 ≈ 6.7 * 10^15 groups 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" at p, and check whether the 4th corner q + r - p is in the set. That eliminates one loop, but 20,000^3 is still around 10^12 operations.

    Can we lock in a square using only 2 points instead of 3?

  4. Key geometric insight: 2 points on one side fix at most 2 squares

    Suppose we pick just two distinct points p1 = (x1, y1) and p2 = (x2, y2) and treat the segment between them as one side of a candidate square.

    The arrow (vector) from p1 to p2 moves right by dx = x2 - x1 and up by dy = 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) and p2 = (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, matching 2^2 + 1^2 = 5, and their dot product is 2 * (-1) + 1 * 2 = 0 (meaning a perfect 90-degree angle!). - Shifting both p1 and p2 by (-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, and y1 - dx are always exact integers! We simply check if those two target tuples exist in our hash set unique_points — just 4 O(1) lookups per pair of points, bringing the total time down to O(n^2).

  5. Why we divide the total hits by 4

    Wait — if we loop over every unordered pair (p1, p2) with i < 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 are 6 unordered 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 (say AB), 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 to AB, if those points exist). - What when our loop visits a diagonal like AC? Then it treats AC (squared length 18) as a side and looks for corners of a larger tilted square of squared side 18 — it never re-discovers ABCD!

    Therefore, every distinct square in the input contributes exactly 4 hits (one from each of its 4 sides). Integer division side_matches // 4 gives the exact count of distinct squares.

  6. Code the O(n^2) square counter

    Let's assemble count_squares cleanly in three short phases: deduplicate into a set, scan all i < j point pairs checking both 90-degree rotations, and divide side_matches by 4.

    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 // 4
    
  7. Trace Example 4 step by step

    In Example 4, the 9 input entries collapse (0, 2) into 8 unique coordinates forming two 2 x 2 squares 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 = 28 unordered point pairs: - 3 outer edges of Sq L ((0,0)-(2,0), (0,0)-(0,2), (0,2)-(2,2)): each matches Sq L on one side and misses outside -> +3 hits. - 3 outer edges of Sq R ((2,0)-(4,0), (4,0)-(4,2), (2,2)-(4,2)): each matches Sq R on one side and misses outside -> +3 hits. - 1 shared vertical edge (2,0)-(2,2) with (dx, dy) = (0, 2): - +90 deg shift (-2, 0) checks (0,0) and (0,2) -> hits Sq L (+1)! - -90 deg shift (2, 0) checks (4,0) and (4,2) -> hits Sq 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 -> +4 hits. - All 17 remaining pairs (diagonals and long spans): miss at least one rotated corner -> 0 hits.

    Total side_matches = 3 + 3 + 2 + 4 = 12, and 12 // 4 = 3 distinct squares.

  8. Complete solution

    We include both is_square (for Stage 1) and count_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 and 4 * 3 / 2 = 6 pairwise 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 (where N is the input length and n <= N is the number of unique points): Inserting N points into the hash set takes O(N) average time. Then we loop over n * (n - 1) / 2 unordered pairs of unique points, performing 4 O(1) average hash-set lookups per pair.
  • Stage 2 (count_squares) space — O(n): We store each unique (x, y) coordinate once in unique_points and once in distinct_pts.
  • Why O(n^2) is hard to beat when listing squares: A dense k x k grid of n = k^2 integer points already contains roughly n^2 / 12 distinct squares (including tilted ones), so any algorithm that discovers squares one by one must spend at least Omega(n^2) time in the worst case.

Edge cases

  • Fewer than 4 distinct points: Even if points has 100 entries that are all duplicates of 3 coordinates, len(distinct_pts) < 4 returns 0 immediately.
  • Degenerate zero-length "squares": A non-degenerate square is a square with positive side length (s > 0). Deduplicating coordinates in count_squares (and checking side_sq == 0 in is_square) ensures [[3, 3], [3, 3], [3, 3], [3, 3]] returns 0 / 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_square rejects it via the diagonal check diag^2 == 2 * side^2, and count_squares never 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 - dy can reach roughly 3 * 2^31 (requiring 64-bit int64_t / long), and in is_square dx^2 + dy^2 can reach 2^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 satisfy diag^2 == 2 * side^2.
  • Using math.sqrt and 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 +90 and -90 turns tested as sides, every square is found 4 times (// 4). Using ordered pairs (i != j) finds each square 8 times (// 8); using pairs as diagonals finds each square 2 times (// 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 .5 half-integer coordinates and cannot be in our integer set, so we skip the pair; otherwise we divide by 2, look up both corners in unique_points, and divide the final count by 2 (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_points set with a frequency dictionary freq[(x, y)] counting how many times each coordinate appears. Still loop only over pairs of distinct coordinates p1 and p2 so zero-size shapes remain excluded, and whenever a square with corners (p1, p2, p3, p4) is found, add freq[p1] * freq[p2] * freq[p3] * freq[p4] to total before dividing by 4 at 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_points and a running total. When a brand-new point p arrives (ignore it if p is already in unique_points), pair p with every existing point q and test both 90-degree turns of side p-q; because every newly completed square touches p along two of its sides, add new_hits // 2 to total in O(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 if x1 != x2 and abs(x2 - x1) == abs(y2 - y1), in which case the other two corners must be (x1, y2) and (x2, y1). Even better, group points by x-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 from O(n^2) to O(n * sqrt(n)).

Follow-up questions

Similar questions

More Purestorage interview questions

All 4 Purestorage questions →