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
INPUTALGORITHMRESULT(0,0)(2,2)(2,0)Polygon Vertices:[[0,0], [0,2], [2,2], [2,0]]1Cross Productsx[i] × y[j] - x[j] × y[i]2Sum All TermsRunning total of products3Final Calculation|sum| ÷ 2 = areaShoelace FormulaOne pass through vertices4.0Square unitsPolygon AreaCalculated usingshoelace formulaKey Insight:The shoelace formula calculates polygon area by summing cross productsof adjacent vertices, eliminating the need to triangulate the shape.TutorialsPoint - Polygon Area Calculator | Shoelace Formula
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
25.5K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen