Algorithmsarea calculation

Understanding Area Calculation

TT
Testlaa Team
May 15, 20261 min read

Area calculation on grids or polygons answers “how many cells are covered?” or “what is the enclosed region size?”—often via inclusion–exclusion, sweep line, or the shoelace formula.

Why this shows up in the real world

Floor plans, land plots, and rectangle union problems in interviews all reduce to counting unit squares or applying signed area formulas.

Core idea (explained for students)

For axis-aligned rectangles on a compressed grid: mark events (open/close), sweep x, maintain active y-intervals and add covered area per strip. For polygon vertices (x_i,y_i), shoelace: A = 1/2 |Σ x_i y_{i+1} - x_{i+1} y_i|.

Try this in Python

def shoelace_area(pts: list[tuple[int, int]]) -> float:
    n = len(pts)
    s = 0
    for i in range(n):
        x1, y1 = pts[i]
        x2, y2 = pts[(i + 1) % n]
        s += x1 * y2 - x2 * y1
    return abs(s) / 2


# Unit square
print(shoelace_area([(0, 0), (2, 0), (2, 2), (0, 2)]))

Common mistakes

  • Double-counting overlapping rectangles.
  • Integer overflow on large coordinates before compression.
  • Shoelace with vertices in wrong order (self-intersecting).

Key takeaways

  • Compress coordinates first when the grid is sparse.
  • For union of rectangles, sweep + segment tree or sorted active set on y.

Tags:

Coordinate tricksPythonStudents