(Translated by https://www.hiragana.jp/)
Check whether a given point lies inside a triangle or not - GeeksforGeeks
Open In App

Check whether a given point lies inside a triangle or not

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three corner points of a triangle, and one more point P. Write a function to check whether P lies within the triangle or not.

Example:

Input: A = (0, 0), B = (10, 30), C = (20, 0), P(10, 15)
Output: Inside
Explanation:
B(10,30)
/ \
/ \
/ \
/ P \ P'
/ \
A(0,0) ----------- C(20,0)
Input: A = (0, 0), B = (10, 30), C = (20, 0), P(30, 15)
Output: Outside
Explanation:
B(10,30)
/ \
/ \
/ \
/ \ P
/ \
A(0,0) ----------- C(20,0)
 


Solution: 
Let the coordinates of the three corners be (x1, y1), (x2, y2), and (x3, y3). And coordinates of the given point P be (x, y)

  1. Calculate the area of the given triangle, i.e., the area of the triangle ABC in the above diagram. 
    Area A = [ x1(y2 - y3) + x2(y3 - y1) + x3(y1-y2)]/2 
  2. Calculate the area of the triangle PAB. We can use the same formula for this. Let this area be A1. 
  3. Calculate the area of the triangle PBC. Let this area be A2. 
  4. Calculate the area of the triangle PAC. Let this area be A3. 
  5. If P lies inside the triangle, then A1 + A2 + A3 must be equal to A. 
C++
C Java Python C# JavaScript PHP

Output
Inside

Time Complexity: O(1)
Auxiliary Space: O(1)

[embed]https://www.youtube.com/watch?v=H9qu9Xptf-w%5B/embed%5D

Exercise: Given coordinates of four corners of a rectangle, and a point P. Write a function to check whether P lies inside the given rectangle or not.

Another Approach - Using Barycentric Coordinate Method: Below is the algorithm to check if a point P lies inside a triangle ABC using the Barycentric Coordinate Method:

  • Define a function "isInsideTriangle" that takes four input parameters: A, B, C, and P.
  • Calculate the barycentric coordinates of point P with respect to the triangle ABC. To do this, we first need to calculate the area of the triangle ABC. We can use the cross product to find the area of the triangle ABC as:

Area(ABC) = 0.5 * ||AB x AC||, where ||AB x AC|| is the magnitude of the cross product of vectors AB and AC.

  • Then, we can calculate the barycentric coordinates of point P as:
    1. a = 0.5 * ||PB x PC|| / Area(ABC)
    2. b = 0.5 * ||PC x PA|| / Area(ABC)
    3. c = 0.5 * ||PA x PB|| / Area(ABC), where PB, PC, and PA are vectors from point P to vertices B, C, and A, respectively.
  • If all three barycentric coordinates are non-negative, then the point P lies inside the triangle ABC. Return "Inside". Otherwise, point P lies outside the triangle ABC. Return "Outside".

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output
Inside

Time Complexity: O(1)
Auxiliary Space: O(1)


Check whether a given point lies inside a triangle or not
Practice Tags :

Similar Reads