VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solution-polygon-area/

⇱ CSES Solution - Polygon Area - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solution - Polygon Area

Last Updated : 31 Jan, 2026

Your task is to calculate the area of a given polygon.

The polygon consists of n vertices (x1,y1),(x2,y2),.....(xn,yn). The vertices (xi,yi) and (xi+1,yi+1) are adjacent for i=1,2,....,n-1, and the vertices (x1,y1) and (xn,yn) are also adjacent.

Example:

Input: vertices[] = {{1, 1}, {4, 2}, {3, 5}, {1, 4}}
Output: 16

Input: vertices[] = {{1, 3}, {5, 6}, {2, 5}, {1, 4}}
Output: 6

Approach:

The idea is to use Shoelace formula calculates the area of a polygon as half of the absolute difference between the sum of products of x-coordinates and y-coordinates of consecutive vertices.

Shoelace formula Formula:

  • The formula involves summing the products of the x-coordinates of adjacent vertices and the y-coordinates of the next adjacent vertices, and then subtracting the products of the y-coordinates of adjacent vertices and the x-coordinates of the next adjacent vertices.
  • The result is multiplied by 0.5 to get the area of the polygon.

Steps-by-step approach:

  • Calculate the area using the shoelace formula:
    • Initialize a variable area to 0.
    • Iterate over the vertices of the polygon.
    • For each vertex i, calculate the product of the x-coordinate of vertex i and the y-coordinate of vertex i+1, and subtract the product of the y-coordinate of vertex i and the x-coordinate of vertex i+1.
    • Add the result to the area variable.
  • Take the absolute value of the area:
    • The shoelace formula can result in a negative area if the polygon is oriented clockwise.
    • To ensure that the area is always positive, take the absolute value of the area variable.
  • Return the absolute value of the area variable.

Below is the implementation of the above approach:


Output
6

Time complexity: O(N), where N is the number of points.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: