Polygon Area Calculator - Problem
Given the coordinates of a polygon's vertices in order, calculate the area of the polygon using the Shoelace formula (also known as the surveyor's formula).
The vertices are provided as a list of [x, y] coordinate pairs. The polygon can be convex or concave, and may even be self-intersecting. For self-intersecting polygons, calculate the absolute area.
The Shoelace formula states that for a polygon with vertices (x₁,y₁), (x₂,y₂), ..., (xₙ,yₙ), the area is:
Area = ½ × |∑(xᵢ × yᵢ₊₁ - xᵢ₊₁ × yᵢ)|
where the sum runs from i = 0 to n-1 and indices are taken modulo n.
Input & Output
Example 1 — Simple Square
$
Input:
vertices = [[0,0], [0,2], [2,2], [2,0]]
›
Output:
4.0
💡 Note:
A square with side length 2 has area = 2 × 2 = 4.0
Example 2 — Triangle
$
Input:
vertices = [[0,0], [3,0], [3,4]]
›
Output:
6.0
💡 Note:
Right triangle with base 3 and height 4: area = ½ × 3 × 4 = 6.0
Example 3 — Complex Polygon
$
Input:
vertices = [[1,1], [4,1], [4,3], [2,3], [2,2], [1,2]]
›
Output:
4.0
💡 Note:
L-shaped polygon calculated using shoelace formula gives area 4.0
Constraints
- 3 ≤ vertices.length ≤ 104
- -106 ≤ vertices[i][0], vertices[i][1] ≤ 106
- Vertices are given in order (clockwise or counterclockwise)
- Polygon may be self-intersecting
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code