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 <= 1000 for every (x, y) in points (all coordinates are integers)
  • A valid square requires four distinct coordinate locations.

Step-by-step walkthrough

  1. Understand the input, tilted squares, and duplicates

    We are given up to n = 500 integer 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 Python set directly until converted to (x, y) tuples.
  2. 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] with s > 0.

    At n = 500, the number of 4-point subsets is 500 * 499 * 498 * 497 / 24, which is roughly 2.6 billion groups — far too slow (O(n^4)).

    To drop from O(n^4) to O(n^2), we store all distinct points in a hash set (a hash-table collection supporting O(1) average membership checks). If picking just 2 points uniquely determines where the other 2 corners must sit, we only have 500 * 499 / 2 = 124,750 pairs to inspect!

  3. 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 points A = (ax, ay) and C = (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) / 2 2. Half-diagonal vector h = C - M (using dx = cx - ax and dy = cy - ay): hx = (cx - ax) / 2 = dx / 2, hy = (cy - ay) / 2 = dy / 2 3. Rotate h by +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, so B and D are guaranteed to be distinct from A, C, and each other!

  4. Stay in exact integers with an evenness check

    Suppose A = (0, 1) and C = (2, 2). Plugging into our formulas gives B = (0.5, 2.5) and D = (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 // 2 without checking evenness first, twice_bx = 0 + 2 - 1 = 1 and 1 // 2 would silently round 0.5 down to 0, 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 by 2:

    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 + ay shows all four numerators actually share the exact same even/odd parity as ax + ay + cx + cy, though checking all four explicitly makes the code completely self-evident.)

  5. Deduplicate and convert points to hashable tuples

    Before running the pair loop, we pass points through 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 distinct
    
  6. Avoid 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 *-------* C
    

    Every real square has 2 diagonals (A-C and B-D), so our unordered pair loop increments diagonal_matches twice per square. Dividing by 2 (diagonal_matches // 2) gives the exact count of distinct squares!

  7. 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 = 1
    
  8. Complete 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 building point_set scans the n points once in O(n) average time. The nested loop then inspects m * (m - 1) / 2 unordered pairs, doing constant integer arithmetic and at most two O(1) average hash-set lookups per pair.
  • Space: O(n). Both pts and point_set store at most n coordinate tuples.

Edge cases

  • Fewer than 4 distinct points (including []): Either the nested loop runs zero times or point_set cannot contain two additional distinct corners, returning 0.
  • Duplicate coordinates in the input: unique_points collapses 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 return None immediately rather than rounding onto an integer point.
  • Negative coordinates: In Python, % 2 always evaluates to 0 or 1 even for negative integers (-3 % 2 == 1), and // 2 divides negative even integers exact-halves (-2 // 2 == -1).

Common mistakes

  • Using // 2, int(...), or round(...) without checking % 2 != 0 first: Floor-dividing an odd numerator snaps a half-integer coordinate like (1.5, 0.5) onto (1, 0), which may happen to be in point_set and 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 with TypeError: 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 points A and B forming side vector (dx, dy) = (bx - ax, by - ay), rotating (dx, dy) by +90 degrees ((-dy, dx)) gives candidate corners A + (-dy, dx) and B + (-dy, dx) on one side of segment AB (no division by 2 or parity check needed!). Checking unordered pairs with both +90 and -90 rotations finds each square once from each of its 4 sides, so you divide by 4 at 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 testing d[0] > 0 and d == [s, s, s, s, 2*s, 2*s]. Far too slow for n = 500, effortless as an automated test oracle for n <= 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 and O(n) space regardless of coordinate magnitude because hash-set lookups depend on point count n, not coordinate span! For huge coordinates (say 10^12), our exact integer parity check avoids IEEE-754 float precision loss (which degrades above 2^53); in fixed-width languages like C++ or Java, use 64-bit long integers since ax + cx - dy can reach 4 * max_coord. (Note that on a dense m x m grid of n = m^2 points there are n * (n - 1) / 12 squares, so any algorithm that inspects each square individually cannot beat O(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 != cx and abs(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 grouping y coordinates per x column (cols[x]) and only pairing points that share the same x coordinate or the same x - y diagonal, while worst-case time remains O(n^2).
  • What changes are needed to output each distinct square's four vertices rather than just the total? Whenever both corner_b and corner_d exist in point_set, canonicalize the four corners by sorting them into square = tuple(sorted([pts[i], pts[j], corner_b, corner_d])) and insert square into a found_squares set. Because both diagonals of the same square produce the exact same sorted 4-tuple, the set automatically deduplicates them, and you can return list(found_squares) (or sorted(found_squares)).

Follow-up questions

Similar questions

More 6Sense interview questions

All 1 6Sense questions →