Count Squares Spanned by Crossing Vertical and Horizontal Segments
Arrays & HashingAuto-graded · 27 test casesLast updated
Count axis-aligned squares whose four corners all lie where a vertical segment meets a horizontal one, using per-row bitmasks and pairwise row comparison.
You are given two lists of straight segments on a plane: one list of vertical segments and one list of horizontal segments. Each segment is given by two endpoints, and each endpoint is an [x, y] pair of integers.
A point is a crossing point if it lies on at least one vertical segment and on at least one horizontal segment. Segments are closed, so their endpoints count as part of them. A vertical segment that stops exactly on a horizontal one still creates a crossing point.
Your task is to count the axis-aligned squares of positive side length whose four corners are all crossing points.
Details
vert_segs[i] = [[x1, y1], [x2, y2]]withx1 == x2andy1 != y2.horiz_segs[j] = [[x1, y1], [x2, y2]]withy1 == y2andx1 != x2.- The two endpoints of a segment may be listed in either order.
- A square is described by a lower-left corner
(x, y)and a sides > 0. Its corners are(x, y),(x + s, y),(x, y + s)and(x + s, y + s), and all four must be crossing points. - Only squares count. Rectangles with unequal sides do not.
- Each distinct square is counted once. Squares of every size count, including ones that contain smaller squares.
- Only the four corners need to be crossing points. Because x-coordinates of vertical segments are distinct and y-coordinates of horizontal segments are distinct, each side of a counted square automatically lies on given segments.
Return the number of such squares as an integer.
Constraints
1 <= len(vert_segs) <= 3001 <= len(horiz_segs) <= 300- All coordinates are integers in
[-10^6, 10^6]. - No two vertical segments share the same x-coordinate.
- No two horizontal segments share the same y-coordinate.
- The answer fits in a 64-bit integer.
Examples
Example 1
Input: count_grid_squares([[[1, 0], [1, 3]], [[2, 3], [2, 0]]], [[[0, 1], [3, 1]], [[3, 2], [0, 2]]])
Output: 1
Example 2
Input: count_grid_squares([[[0, 0], [0, 2]], [[1, 0], [1, 2]], [[2, 0], [2, 2]]], [[[0, 0], [2, 0]], [[0, 1], [2, 1]], [[0, 2], [2, 2]]])
Output: 5
Example 3
Input: count_grid_squares([[[0, 0], [0, 4]], [[2, 0], [2, 4]], [[3, 1], [3, 4]]], [[[0, 0], [3, 0]], [[0, 2], [3, 2]], [[-1, 3], [3, 3]]])
Output: 2
Hints
Hint 1
Every crossing point is determined by one vertical segment (its x) and one horizontal segment (its y). Start by working out, for each horizontal segment, exactly which verticals it meets, remembering that touching at an endpoint counts.
Hint 2
A square is fixed by its bottom row, top row and left column. For a pair of rows with gap s, you need columns x where both rows have crossings at x and at x + s. Think of each row as a set of x positions.
Hint 3
Store each row's crossing x positions as a bitmask. For two rows, AND the masks, then AND the result with itself shifted right by s, and count set bits. Compressing coordinates (subtracting minimums, dividing by one shared gcd) keeps the masks short.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A square is fully determined by its bottom row y1, its top row y2 and its left column x. The side is s = y2 - y1, and the corners are (x, y1), (x + s, y1), (x, y2), (x + s, y2).
- Normalize the segments. Turn each vertical segment into
(x, ylo, yhi)and each horizontal one into(y, xlo, xhi), so the endpoint order no longer matters. - Build a bitmask per row. For each horizontal segment at height
y, test every vertical segment with closed comparisons (xlo <= x <= xhiandylo <= y <= yhi). Set bitxin that row's mask whenever they meet. Rows with fewer than two crossings cannot hold the bottom or top side of a square and are dropped. - Compress coordinates. Subtract the minimum x and minimum y, then divide all offsets by one shared gcd
gof all x-offsets and y-offsets. Using the samegon both axes keeps equal lengths equal, so squares stay squares, and the bitmasks get much narrower on coarse lattices. Ifg == 0, there is one vertical and one horizontal segment, so there is at most one crossing and the answer is 0. - Compare pairs of rows. For rows
y1 < y2with masksm1,m2, lets = y2 - y1. Thenc = m1 & m2holds the columns that are crossings in both rows, andc & (c >> s)keeps the columnsxwherex + sis also inc. Its popcount is the number of squares for this row pair. - Prune. Precompute all differences between pairs of vertical x-positions. If
sis not among them, no square of that side exists and the pair is skipped.
Why it is correct
- Since x-values of verticals are distinct and y-values of horizontals are distinct, a crossing at
(x, y)exists exactly when the one horizontal segment atyand the one vertical segment atxboth contain that point. The masks encode this exactly, with endpoint touches included. - Every square has a unique (bottom row, top row, left column) triple. Rows are sorted and distinct, so each pair is visited once with
s > 0, and each validxcontributes exactly one set bit. - Non-square rectangles are never counted because only columns exactly
sapart are matched. - Dividing by a common
gmaps crossings one-to-one onto a smaller grid and preserves side equality, so the count is unchanged.
Complexity
With V vertical and H horizontal segments and a scaled x-span of W bits:
- Building masks:
O(V * H). - Gap set:
O(V^2). - Row-pair loop:
O(H^2 * W / 64)word operations in the worst case, usually much less thanks to pruning and compression. - Space:
O(H * W / 64 + V^2).
This beats the brute-force approach of trying every pair of rows and columns and checking four corners, which is O(H^2 * V^2).
An optional speedup for finding the crossings themselves is a sweep line over x with an ordered set of active horizontal y-values, giving O((V + H) log H + K) for K crossings. Process events at equal x as insert, then query, then remove, so that endpoint touches are not missed.
Reference solution
from math import gcd
from typing import List
def count_grid_squares(vert_segs: List[List[List[int]]], horiz_segs: List[List[List[int]]]) -> int:
# Normalize: verticals -> (x, ylo, yhi), horizontals -> (y, xlo, xhi)
vs = []
for (x1, y1), (x2, y2) in vert_segs:
vs.append((x1, min(y1, y2), max(y1, y2)))
hs = []
for (x1, y1), (x2, y2) in horiz_segs:
hs.append((y1, min(x1, x2), max(x1, x2)))
xmin = min(v[0] for v in vs)
ymin = min(h[0] for h in hs)
# One shared scale factor for both axes keeps side lengths consistent.
g = 0
for v in vs:
g = gcd(g, v[0] - xmin)
for h in hs:
g = gcd(g, h[0] - ymin)
if g == 0:
return 0
# Each row: (scaled y, bitmask of scaled x positions of crossing points)
rows = []
for y, xl, xr in hs:
mask = 0
for x, yl, yr in vs:
if xl <= x <= xr and yl <= y <= yr:
mask |= 1 << ((x - xmin) // g)
if mask & (mask - 1): # at least two crossings needed in a row
rows.append(((y - ymin) // g, mask))
rows.sort()
# All possible gaps between two vertical segments (scaled).
xs = sorted((v[0] - xmin) // g for v in vs)
diffs = set()
for i in range(len(xs)):
for j in range(i + 1, len(xs)):
diffs.add(xs[j] - xs[i])
total = 0
for i in range(len(rows)):
y1, m1 = rows[i]
for j in range(i + 1, len(rows)):
y2, m2 = rows[j]
s = y2 - y1
if s in diffs:
c = m1 & m2
if c:
total += bin(c & (c >> s)).count("1")
return total