Last Updated: 5 Oct, 2020

Area Under Curve

Moderate
Asked in companies
Jio Platforms LimitedIntello Labs

Problem statement

Given a curve whose edges are parallel to either X-axis or Y-axis, you need to find the area under this curve along the X-axis. The curve will be given in the form of a linked list containing N nodes, where each node represents the coordinates of the curve.

The area under the curve along the X-axis is defined as the total area covered by the curve and the line Y = 0. See the sample explanation figure below for further clarification.

Note
1. The coordinates will be given in non-descending order of X coordinate from start to end of the linked list.

2. All the coordinates will be pairwise distinct i.e there are no two coordinates (X1, Y1) and (X2, Y2) such that X1 =  X2 and Y1 = Y2 and there will be an edge between every two consecutive coordinates.

3. The first coordinate and the last coordinate in the input can be assumed as the starting point and the ending point of the curve respectively and there will not be an edge between these two coordinates.
Input Format:
The first line contains a single integer T denoting the number of test cases.

The first and the only line of each test case will contain 2 * N +1  linked list elements (separated by space and terminated by -1), where 'N' is the total number of coordinates. 
Each node consists of two parts (X coordinate and Y coordinate). 
Output Format:
For each test case, print a single integer denoting the total area under the given curve. 
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function and return the answer.
Constraints:
1 <= T <= 10
1 <= N <= 10^4
-10^4 <= X, Y <= 10^4

Time Limit: 1 sec

Approaches

01 Approach

  1. As given in the problem statement, the edges of the curve will always be parallel to either of the two axes, so we can assume that for every two consecutive coordinates either the X-coordinate or the y-coordinate will be the same for them.
  2. Thus we can always imagine a rectangle between every two consecutive coordinates of the curve and the corresponding coordinates on the X-axis.
  3. If the x-coordinate of the two consecutive points are the same, then the area of the rectangle formed will be 0, otherwise, the area will be (X2 - X1) * Y, where Y is the Y-coordinate of both the points and X1 and X2 are X-coordinates of first and the second point respectively.