The Wayback Machine - https://web.archive.org/web/20240913072301/https://www.geeksforgeeks.org/tangents-two-convex-polygons/
Open In App

Tangents between two Convex Polygons

Last Updated : 08 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two convex polygons, we need to find the lower and upper tangents to these polygons. 
As shown in the figure below, T_{RL}         and T_{LR}         show upper and lower tangent respectively.
 

tangent


Examples: 
 

Input : First Polygon  : {(2, 2), (3, 3), (5, 2), (4, 0), (3, 1)} 
Second Polygon : {(-1, 0), (0, 1), (1, 0), (0, -2)}.
Output : Upper Tangent - line joining (0,1) and (3,3)
Lower Tangent - line joining (0,-2) and (4,0)


Overview: 
Let’s have two convex polygons as shown, 
 

tangent2


For finding the upper tangent, we start by taking two points. The rightmost point of a and leftmost point of b. The line joining them is labelled as 1. As this line passes through the polygon b (is not above polygon b) so we take the anti-clockwise next point on b, the line is labelled 2. Now the line is above the polygon b, fine! But the line is crossing the polygon a, so we move to the clockwise next point, labelled as 3 in the picture. This again crossing the polygon a so we move to line 4. This line is crossing b so we move to line 5. Now this line is crossing neither of the points. So this is the upper tangent for the given polygons. 
For finding the lower tangent we need to move inversely through the polygons i.e. if the line is crossing the polygon b we move to clockwise next and to anti-clockwise next if the line is crossing the polygon a.
Algorithm for upper tangent: 
 

L <- line joining the rightmost point of a
and leftmost point of b.
while (L crosses any of the polygons)
{
while(L crosses b)
L <- L' : the point on b moves up.
while(L crosses a)
L <- L' : the point on a moves up.
}


Algorithm for lower tangent: 
 

L <- line joining the rightmost point of a 
and leftmost point of b.
while (L crosses any of the polygons)
{
while (L crosses b)
L <- L' : the point on b moves down.
while (L crosses a)
L <- L' : the point on a moves down.
}


 Example :

CPP
// C++ program to find upper tangent of two polygons.
#include<bits/stdc++.h>
using namespace std;

// stores the center of polygon (It is made
// global because it is used in compare function)
pair<int,int> mid;

// determines the quadrant of a point
// (used in compare())
int quad(pair<int,int> p)
{
    if (p.first >= 0 && p.second >= 0)
        return 1;
    if (p.first <= 0 && p.second >= 0)
        return 2;
    if (p.first <= 0 && p.second <= 0)
        return 3;
    return 4;
}

// Checks whether the line is crossing the polygon
int orientation(pair<int,int> a, pair<int,int> b,
                                 pair<int,int> c)
{
    int res = (b.second-a.second)*(c.first-b.first) -
              (c.second-b.second)*(b.first-a.first);

    if (res == 0)
        return 0;
    if (res > 0)
        return 1;
    return -1;
}

// compare function for sorting
bool compare(pair<int,int> p1, pair<int,int> q1)
{
    pair<int,int> p = make_pair(p1.first - mid.first,
                                p1.second - mid.second);
    pair<int,int> q = make_pair(q1.first - mid.first,
                                q1.second - mid.second);

    int one = quad(p);
    int two = quad(q);

    if (one != two)
        return (one < two);
    return (p.second*q.first < q.second*p.first);
}

// Finds upper tangent of two polygons 'a' and 'b'
// represented as two vectors.
void findUpperTangent(vector<pair<int,int> > a,
                      vector<pair<int,int> > b)
{
    // n1 -> number of points in polygon a
    // n2 -> number of points in polygon b
    int n1 = a.size(), n2 = b.size();

    // To find a point inside the convex polygon(centroid),
    // we sum up all the coordinates and then divide  by
    // n(number of points). But this would be a floating-point
    // value. So to get rid of this we multiply points
    // initially with n1 and then find the centre and
    // then divided it by n1 again.
    // Similarly we do divide and multiply for n2 (i.e.,
    // elements of b)

    // maxa and minb are used to check if polygon a
    // is left of b.
    int maxa = INT_MIN;
    for (int i=0; i<n1; i++)
    {
        maxa = max(maxa, a[i].first);
        mid.first  += a[i].first;
        mid.second += a[i].second;
        a[i].first *= n1;
        a[i].second *= n1;
    }

    // sorting the points in counter clockwise order
    // for polygon a
    sort(a.begin(), a.end(), compare);

    for (int i=0; i<n1; i++)
    {
        a[i].first /= n1;
        a[i].second /= n1;
    }

    mid = {0, 0};

    int minb = INT_MAX;
    for (int i=0; i<n2; i++)
    {
        mid.first += b[i].first;
        mid.second += b[i].second;
        minb = min(minb, b[i].first);
        b[i].first *= n2;
        b[i].second *= n2;
    }

    // sorting the points in counter clockwise
    // order for polygon b
    sort(b.begin(), b.end(), compare);

    for (int i=0; i<n2; i++)
    {
        b[i].first/=n2;
        b[i].second/=n2;
    }

    // If a is to the right of b, swap a and b
    // This makes sure a is left of b.
    if (minb < maxa)
    {
        a.swap(b);
        n1 = a.size();
        n2 = b.size();
    }

    // ia -> rightmost point of a
    int ia = 0, ib = 0;
    for (int i=1; i<n1; i++)
        if (a[i].first > a[ia].first)
            ia = i;

    // ib -> leftmost point of b
    for (int i=1; i<n2; i++)
        if (b[i].first < b[ib].first)
            ib=i;

    // finding the upper tangent
    int inda = ia, indb = ib;
    bool done = 0;
    while (!done)
    {
        done = 1;
        while (orientation(b[indb], a[inda], a[(inda+1)%n1]) > 0)
            inda = (inda + 1) % n1;

        while (orientation(a[inda], b[indb], b[(n2+indb-1)%n2]) < 0)
        {
            indb = (n2+indb-1)%n2;
            done = 0;
        }
    }

    cout << "upper tangent (" << a[inda].first << ","
        << a[inda].second << ") (" << b[indb].first
        << "," << b[indb].second << ")\n";
}

// Driver code
int main()
{
    vector<pair<int,int> > a;
    a.push_back({2, 2});
    a.push_back({3, 1});
    a.push_back({3, 3});
    a.push_back({5, 2});
    a.push_back({4, 0});

    vector<pair<int,int> > b;
    b.push_back({0, 1});
    b.push_back({1, 0});
    b.push_back({0, -2});
    b.push_back({-1, 0});

    findUpperTangent(a, b);

    return 0;
}
Java
// Java program to find upper tangent of two polygons.
import java.util.*;

public class UpperTangentFinder {
    // Class representing a 2D point
    static class Point {
        int x, y;

        Point() {
            x = 0;
            y = 0;
        }

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    // Stores the center of polygon (It is made
    // global because it is used in compare function)
    static Point mid = new Point();

    // Determines the quadrant of a point
    // (used in compare())
    static int quad(Point p) {
        if (p.x >= 0 && p.y >= 0)
            return 1;
        if (p.x <= 0 && p.y >= 0)
            return 2;
        if (p.x <= 0 && p.y <= 0)
            return 3;
        return 4;
    }

    // Checks whether the line is crossing the polygon
    static int orientation(Point a, Point b, Point c) {
        int res = (b.y - a.y) * (c.x - b.x) - (c.y - b.y) * (b.x - a.x);

        if (res == 0)
            return 0;
        if (res > 0)
            return 1;
        return -1;
    }

    // Compare function for sorting
    static class PointComparator implements Comparator<Point> {
        public int compare(Point p1, Point p2) {
            Point p = new Point(p1.x - mid.x, p1.y - mid.y);
            Point q = new Point(p2.x - mid.x, p2.y - mid.y);

            int one = quad(p);
            int two = quad(q);

            if (one != two)
                return one - two;
            return p.y * q.x - q.y * p.x;
        }
    }

    // Finds upper tangent of two polygons 'a' and 'b'
    // represented as two lists of points.
    static void findUpperTangent(List<Point> a, List<Point> b) {
        // n1 -> number of points in polygon a
        // n2 -> number of points in polygon b
        int n1 = a.size(), n2 = b.size();

        // To find a point inside the convex polygon (centroid),
        // we sum up all the coordinates and then divide by
        // n (number of points). But this would be a floating-point
        // value. So to get rid of this, we multiply points
        // initially with n1 and then find the center and
        // then divide it by n1 again.
        // Similarly, we do divide and multiply for n2 (i.e.,
        // elements of b)

        // maxa and minb are used to check if polygon a
        // is left of b.
        int maxa = Integer.MIN_VALUE;
        for (int i = 0; i < n1; i++) {
            maxa = Math.max(maxa, a.get(i).x);
            mid.x += a.get(i).x;
            mid.y += a.get(i).y;
            a.get(i).x *= n1;
            a.get(i).y *= n1;
        }

        // Sorting the points in counter-clockwise order
        // for polygon a
        a.sort(new PointComparator());

        for (int i = 0; i < n1; i++) {
            a.get(i).x /= n1;
            a.get(i).y /= n1;
        }

        mid.x = 0;
        mid.y = 0;

        int minb = Integer.MAX_VALUE;
        for (int i = 0; i < n2; i++) {
            mid.x += b.get(i).x;
            mid.y += b.get(i).y;
            minb = Math.min(minb, b.get(i).x);
            b.get(i).x *= n2;
            b.get(i).y *= n2;
        }

        // Sorting the points in counter-clockwise
        // order for polygon b
        b.sort(new PointComparator());

        for (int i = 0; i < n2; i++) {
            b.get(i).x /= n2;
            b.get(i).y /= n2;
        }

        // If a is to the right of b, swap a and b
        // This makes sure a is left of b.
        if (minb < maxa) {
            List<Point> temp = a;
            a = b;
            b = temp;
            n1 = a.size();
            n2 = b.size();
        }

        // ia -> rightmost point of a
        int ia = 0, ib = 0;
        for (int i = 1; i < n1; i++) {
            if (a.get(i).x > a.get(ia).x)
                ia = i;
        }

        // ib -> leftmost point of b
        for (int i = 1; i < n2; i++) {
            if (b.get(i).x < b.get(ib).x)
                ib = i;
        }

        // Finding the upper tangent
        int inda = ia, indb = ib;
        boolean done = false;
        while (!done) {
            done = true;
            while (orientation(b.get(indb), a.get(inda), a.get((inda + 1) % n1)) > 0)
                inda = (inda + 1) % n1;

            while (orientation(a.get(inda), b.get(indb), b.get((n2 + indb - 1) % n2)) < 0) {
                indb = (n2 + indb - 1) % n2;
                done = false;
            }
        }

        System.out.println("upper tangent (" + a.get(inda).x + "," + a.get(inda).y + ") (" + b.get(indb).x + "," + b.get(indb).y + ")");
    }

    // Driver code
    public static void main(String[] args) {
        List<Point> a = new ArrayList<>();
        a.add(new Point(2, 2));
        a.add(new Point(3, 1));
        a.add(new Point(3, 3));
        a.add(new Point(5, 2));
        a.add(new Point(4, 0));

        List<Point> b = new ArrayList<>();
        b.add(new Point(0, 1));
        b.add(new Point(1, 0));
        b.add(new Point(0, -2));
        b.add(new Point(-1, 0));

        findUpperTangent(a, b);
    }
}
Python
# program to find upper tangent of two polygons.
from functools import cmp_to_key

# stores the centre of polygon (It is made
# global because it is used in compare function)
mid = [0, 0]

# determines the quadrant of a point
# (used in compare())
def quad(p):
    if p[0] >= 0 and p[1] >= 0:
        return 1
    if p[0] <= 0 and p[1] >= 0:
        return 2
    if p[0] <= 0 and p[1] <= 0:
        return 3
    return 4

  
# Checks whether the line is crossing the polygon
def orientation(a, b, c):
    res = (b[1]-a[1]) * (c[0]-b[0]) - (c[1]-b[1]) * (b[0]-a[0])
    if res == 0:
        return 0
    if res > 0:
        return 1
    return -1

  
# compare function for sorting
def compare(p1, q1):
    p = [p1[0]-mid[0], p1[1]-mid[1]]
    q = [q1[0]-mid[0], q1[1]-mid[1]]
    one = quad(p)
    two = quad(q)

    if one != two:
        if one < two:
            return -1
        return 1
    if p[1]*q[0] < q[1]*p[0]:
        return -1
    return 1

  
#  Finds upper tangent of two polygons 'a' and 'b'
# represented as two vectors.
def findUpperTangent(a, b):
    global mid
    # n1 -> number of points in polygon a
    # n2 -> number of points in polygon b
    n1, n2 = len(a), len(b)

    # To find a point inside the convex polygon(centroid),
    # we sum up all the coordinates and then divide  by
    # n(number of points). But this would be a floating-point
    # value. So to get rid of this we multiply points
    # initially with n1 and then find the centre and
    # then divided it by n1 again.
    # Similarly we do divide and multiply for n2 (i.e.,
    # elements of b)

    # maxa and minb are used to check if polygon a
    # is left of b.
    maxa = float('-inf')
    for i in range(n1):
        maxa = max(maxa, a[i][0])
        mid[0] += a[i][0]
        mid[1] += a[i][1]
        a[i][0] *= n1
        a[i][1] *= n1

    # sorting the points in counter clockwise order
    # for polygon a
    a = sorted(a, key=cmp_to_key(compare))
    for i in range(n1):
        a[i][0] /= n1
        a[i][1] /= n1

    mid = [0, 0]
    minb = float('inf')
    for i in range(n2):
        minb = min(minb, b[i][0])
        mid[0] += b[i][0]
        mid[1] += b[i][1]
        b[i][0] *= n2
        b[i][1] *= n2

    # sorting the points in counter clockwise
    # order for polygon b
    sorted(b, key=cmp_to_key(compare))
    for i in range(n2):
        b[i][0] /= n2
        b[i][1] /= n2

    # If a is to the right of b, swap a and b
    # This makes sure a is left of b.
    if minb < maxa:
        a, b = b, a
        n1, n2 = n2, n1

    ia, ib = 0, 0
    # ia -> leftmost point of a
    for i in range(1, n1):
        if a[i][0] > a[ia][0]:
            ia = i

    # ib -> leftmost point of b
    for i in range(1, n2):
        if b[i][0] < b[ib][0]:
            ib = i

    # finding the upper tangent
    inda, indb = ia, ib
    done = 0
    while not done:
        done = 1
        while orientation(b[indb], a[inda], a[(inda+1) % n1]) >= 0:
            inda = (inda + 1) % n1

        while orientation(a[inda], b[indb], b[(n2+indb-1) % n2]) <= 0:
            indb = (n2 + indb - 1) % n2
            done = 0

    print('upper tangent (%d, %d) (%d, %d)' %
          (a[inda][0], a[inda][1], b[indb][0], b[indb][1]))


# Driver Code
if __name__ == '__main__':
    a = []
    a.append([2, 2])
    a.append([3, 1])
    a.append([3, 3])
    a.append([5, 2])
    a.append([4, 0])

    b = []
    b.append([0, 1])
    b.append([1, 0])
    b.append([0, -2])
    b.append([-1, 0])

    findUpperTangent(a, b)
C#
using System;
using System.Collections.Generic;

public class UpperTangentFinder
{
    // Class representing a 2D point
    public class Point
    {
        public int x, y;

        public Point()
        {
            x = 0;
            y = 0;
        }

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    // Stores the center of polygon (It is made
    // global because it is used in compare function)
    static Point mid = new Point();

    // Determines the quadrant of a point
    // (used in compare())
    static int Quad(Point p)
    {
        if (p.x >= 0 && p.y >= 0)
            return 1;
        if (p.x <= 0 && p.y >= 0)
            return 2;
        if (p.x <= 0 && p.y <= 0)
            return 3;
        return 4;
    }

    // Checks whether the line is crossing the polygon
    static int Orientation(Point a, Point b, Point c)
    {
        int res = (b.y - a.y) * (c.x - b.x) - (c.y - b.y) * (b.x - a.x);

        if (res == 0)
            return 0;
        if (res > 0)
            return 1;
        return -1;
    }

    // Compare function for sorting
    public class PointComparer : IComparer<Point>
    {
        public int Compare(Point p1, Point p2)
        {
            Point p = new Point(p1.x - mid.x, p1.y - mid.y);
            Point q = new Point(p2.x - mid.x, p2.y - mid.y);

            int one = Quad(p);
            int two = Quad(q);

            if (one != two)
                return one - two;
            return p.y * q.x - q.y * p.x;
        }
    }

    // Finds upper tangent of two polygons 'a' and 'b'
    // represented as two lists of points.
    static void FindUpperTangent(List<Point> a, List<Point> b)
    {
        // n1 -> number of points in polygon a
        // n2 -> number of points in polygon b
        int n1 = a.Count, n2 = b.Count;

        // To find a point inside the convex polygon (centroid),
        // we sum up all the coordinates and then divide by
        // n (number of points). But this would be a floating-point
        // value. So to get rid of this, we multiply points
        // initially with n1 and then find the center and
        // then divide it by n1 again.
        // Similarly, we do divide and multiply for n2 (i.e.,
        // elements of b)

        // maxa and minb are used to check if polygon a
        // is left of b.
        int maxa = int.MinValue;
        for (int i = 0; i < n1; i++)
        {
            maxa = Math.Max(maxa, a[i].x);
            mid.x += a[i].x;
            mid.y += a[i].y;
            a[i].x *= n1;
            a[i].y *= n1;
        }

        // Sorting the points in counter-clockwise order
        // for polygon a
        a.Sort(new PointComparer());

        for (int i = 0; i < n1; i++)
        {
            a[i].x /= n1;
            a[i].y /= n1;
        }

        mid.x = 0;
        mid.y = 0;

        int minb = int.MaxValue;
        for (int i = 0; i < n2; i++)
        {
            mid.x += b[i].x;
            mid.y += b[i].y;
            minb = Math.Min(minb, b[i].x);
            b[i].x *= n2;
            b[i].y *= n2;
        }

        // Sorting the points in counter-clockwise
        // order for polygon b
        b.Sort(new PointComparer());

        for (int i = 0; i < n2; i++)
        {
            b[i].x /= n2;
            b[i].y /= n2;
        }

        // If a is to the right of b, swap a and b
        // This makes sure a is left of b.
        if (minb < maxa)
        {
            List<Point> temp = a;
            a = b;
            b = temp;
            n1 = a.Count;
            n2 = b.Count;
        }

        // ia -> rightmost point of a
        int ia = 0, ib = 0;
        for (int i = 1; i < n1; i++)
        {
            if (a[i].x > a[ia].x)
                ia = i;
        }

        // ib -> leftmost point of b
        for (int i = 1; i < n2; i++)
        {
            if (b[i].x < b[ib].x)
                ib = i;
        }

        // Finding the upper tangent
        int inda = ia, indb = ib;
        bool done = false;
        while (!done)
        {
            done = true;
            while (Orientation(b[indb], a[inda], a[(inda + 1) % n1]) > 0)
                inda = (inda + 1) % n1;

            while (Orientation(a[inda], b[indb], b[(n2 + indb - 1) % n2]) < 0)
            {
                indb = (n2 + indb - 1) % n2;
                done = false;
            }
        }

        Console.WriteLine("upper tangent (" + a[inda].x + "," + a[inda].y + ") (" + b[indb].x + "," + b[indb].y + ")");
    }

    // Driver code
    public static void Main(string[] args)
    {
        List<Point> a = new List<Point>();
        a.Add(new Point(2, 2));
        a.Add(new Point(3, 1));
        a.Add(new Point(3, 3));
        a.Add(new Point(5, 2));
        a.Add(new Point(4, 0));

        List<Point> b = new List<Point>();
        b.Add(new Point(0, 1));
        b.Add(new Point(1, 0));
        b.Add(new Point(0, -2));
        b.Add(new Point(-1, 0));

        FindUpperTangent(a, b);
    }
}
JavaScript
// Javascript program to find upper tangent of two polygons.

// Stores the center of the polygon (made global for use in compare function)
let mid = [0, 0];

// Determines the quadrant of a point (used in compare())
function quad(p) {
    if (p[0] >= 0 && p[1] >= 0) {
        return 1;
    }
    if (p[0] <= 0 && p[1] >= 0) {
        return 2;
    }
    if (p[0] <= 0 && p[1] <= 0) {
        return 3;
    }
    return 4;
}

// Checks whether the line is crossing the polygon
function orientation(a, b, c) {
    const res = (b[1] - a[1]) * (c[0] - b[0]) - (c[1] - b[1]) * (b[0] - a[0]);
    if (res === 0) {
        return 0;
    }
    if (res > 0) {
        return 1;
    }
    return -1;
}

// Compare function for sorting
function compare(p1, q1) {
    const p = [p1[0] - mid[0], p1[1] - mid[1]];
    const q = [q1[0] - mid[0], q1[1] - mid[1]];
    const one = quad(p);
    const two = quad(q);

    if (one !== two) {
        if (one < two) {
            return -1;
        }
        return 1;
    }
    if (p[1] * q[0] < q[1] * p[0]) {
        return -1;
    }
    return 1;
}

// Finds upper tangent of two polygons 'a' and 'b' represented as two arrays of points.
function findUpperTangent(a, b) {
    // n1 -> number of points in polygon a
    // n2 -> number of points in polygon b
    let n1 = a.length;
    let n2 = b.length;

    // To find a point inside the convex polygon (centroid),
    // we sum up all the coordinates and then divide by
    // n (number of points). But this would be a floating-point
    // value. So to get rid of this we multiply points
    // initially with n1 and then find the center and
    // then divide it by n1 again.
    // Similarly, we do divide and multiply for n2 (i.e.,
    // elements of b)

    // maxa and minb are used to check if polygon a
    // is left of b.
    let maxa = Number.NEGATIVE_INFINITY;
    for (let i = 0; i < n1; i++) {
        maxa = Math.max(maxa, a[i][0]);
        mid[0] += a[i][0];
        mid[1] += a[i][1];
        a[i][0] *= n1;
        a[i][1] *= n1;
    }

    // Sorting the points in counterclockwise order for polygon a
    a.sort((p1, p2) => compare(p1, p2));
    for (let i = 0; i < n1; i++) {
        a[i][0] /= n1;
        a[i][1] /= n1;
    }

    mid = [0, 0];
    let minb = Number.POSITIVE_INFINITY;
    for (let i = 0; i < n2; i++) {
        minb = Math.min(minb, b[i][0]);
        mid[0] += b[i][0];
        mid[1] += b[i][1];
        b[i][0] *= n2;
        b[i][1] *= n2;
    }

    // Sorting the points in counterclockwise order for polygon b
    b.sort((p1, p2) => compare(p1, p2));
    for (let i = 0; i < n2; i++) {
        b[i][0] /= n2;
        b[i][1] /= n2;
    }

    // If a is to the right of b, swap a and b
    // This makes sure a is left of b.
    if (minb < maxa) {
        [a, b] = [b, a];
        [n1, n2] = [n2, n1];
    }

    let ia = 0; // leftmost point of a
    for (let i = 1; i < n1; i++) {
        if (a[i][0] > a[ia][0]) {
            ia = i;
        }
    }

    let ib = 0; // leftmost point of b
    for (let i = 1; i < n2; i++) {
        if (b[i][0] < b[ib][0]) {
            ib = i;
        }
    }

    // Finding the upper tangent
    let inda = ia;
    let indb = ib;
    let done = 0;
    while (!done) {
        done = 1;
        while (orientation(b[indb], a[inda], a[(inda + 1) % n1]) >= 0) {
            inda = (inda + 1) % n1;
        }

        while (orientation(a[inda], b[indb], b[(n2 + indb - 1) % n2]) <= 0) {
            indb = (n2 + indb - 1) % n2;
            done = 0;
        }
    }

    console.log(`Upper tangent (${a[inda][0]}, ${a[inda][1]}) (${b[indb][0]}, ${b[indb][1]})`);
}

// Driver Code
const a = [
    [2, 2],
    [3, 1],
    [3, 3],
    [5, 2],
    [4, 0]
];

const b = [
    [0, 1],
    [1, 0],
    [0, -2],
    [-1, 0]
];

findUpperTangent(a, b);

Output: 
 

Upper tangent (0,1) (3,3)

Time Complexity: O(n1 log (n1) + n2 log(n2)) 
Auxiliary Space: O(1)


Note that the above code only finds upper tangent. We can similarly find lower tangent.
This article is contributed by Aarti_Rathi and Amritya Vagmi and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.

 



Previous Article
Next Article

Similar Reads

Find number of Polygons lying inside each given Polygons on Cartesian Plane
Given N non-intersecting nested polygons, and a 2D array arr[][] of pairs, where each cell of the array represents the coordinates of the vertices of a polygon. The task is to find the count of polygons lying inside each polygon. Examples: Input: N = 3, arr[][][] = {{{-2, 2}, {-1, 1}, {2, 2}, {2, -1}, {1, -2}, {-2, -2}}, {{-1, -1}, {1, -1}, {1, 1}}
10 min read
Dynamic Convex hull | Adding Points to an Existing Convex Hull
Given a convex hull, we need to add a given number of points to the convex hull and print the convex hull after every point addition. The points should be in anti-clockwise order after addition of every point. Examples: Input : Convex Hull : (0, 0), (3, -1), (4, 5), (-1, 4) Point to add : (100, 100) Output : New convex hull : (-1, 4) (0, 0) (3, -1)
15 min read
Ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles
Given two circles of given radii, such that the circles don’t touch each other, the task is to find the ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles. Examples: Input: r1 = 4, r2 = 6 Output: 2:3 Input: r1 = 22, r2 = 43 Output: 22:43 Approach: Let the radii of the
5 min read
Ratio of the distance between the centers of the circles and the point of intersection of two transverse common tangents to the circles
Given two circles, of given radii, such that the circles don’t touch each other. The task is to find the ratio of the distance between the centres of the circles and the point of intersection of two transverse common tangents to the circles.Examples: Input :r1 = 4, r2 = 8 Output :1:2 Input :r1 = 5, r2 = 13 Output :5:13 Approach: Let the radii of th
5 min read
Number of common tangents between two circles if their centers and radius is given
Given two circles with a given radius and centers. The task is to find the number of common tangents between these circles.Examples: Input: x1 = -10, y1 = 8, x2 = 14, y2 = -24, r1 = 30, r2 = 10 Output: 3 Input: x1 = 40, y1 = 8, x2 = 14, y2 = 54, r1 = 39, r2 = 51 Output: 2 Approach: First of all we will check whether the circles touch each other ext
7 min read
Ratio of area of two nested polygons formed by connecting midpoints of sides of a regular N-sided polygon
Given an N-sided polygon, the task is to find the ratio of the area of the Nth to (N + 1)th N-sided regular nested polygons generated by joining the midpoints of the sides of the original polygon. Examples : Input: N = 3Output: 4.000000Explanation: Ratio of the length of the sides formed by joining the mid-points of the triangle with the length of
4 min read
Find the angle between tangents drawn from a given external point to a Circle
Given a positive integer R representing the radius of the circle and the center of the circle (X1, Y1) and another point (X2, Y2) in the cartesian plane, the task is to find the angle between the pair of tangents drawn from the point (X2, Y2) to the circle. Examples: Input: R = 6, (X1, Y1) = (5, 1), (X2, Y2) = (6, 9)Output: 96.1851 Input: R = 4, (X
7 min read
Count of nested polygons that can be drawn by joining vertices internally
Given a regular polygon with N sides. The task is to find the count of polygons that can be drawn from the given polygon by joining the vertices of the given polygon internally. Examples: Input: N = 6Output: 1Explanation: There is only one nested polygon i.e., Triangle whose sides are the chords of the immediate parent polygon i.e., Hexagon. Input:
4 min read
Sum of sides of largest and smallest child polygons possible from a given polygon
Given an integer A representing the external angle (in degrees) of a regular convex polygon, the task is to find the sum of the sides of the largest and smallest secondary polygons formed such that each edge of the secondary polygon is a chord of the primary polygon. If it is not possible to form such polygons, then print "-1". Examples: Input: A =
4 min read
Types of Polygons
Types of Polygons classify all polygons based on various parameters. As we know, a polygon is a closed figure consisting only of straight lines on its edges. In other words, polygons are closed figures made up of more than 2 line segments on a 2-dimensional plane. The word Polygon is made up of two words, the first is "poly" which means many and th
9 min read
Check whether two convex regular polygon have same center or not
Given two positive integers N and M which denotes the sides of the convex regular polygon where N &lt; M, the task is to check whether polygons have the same center or not if N-sided polygon was inscribed in an M-sided polygon.Center of Polygon: Point inside a polygon which is equidistant from each vertex of the polygon. Examples: Input: N = 9, M =
3 min read
Number of ways a convex polygon of n+2 sides can split into triangles by connecting vertices
Given a convex polygon with n+2 sides. The task is to calculate the number of ways in which triangles can be formed by connecting vertices with non-crossing line segments.Examples: Input: n = 1 Output: 1 It is already a triangle so it can only be formed in 1 way.Input: n = 2 Output: 2 It can be cut into 2 triangles by using either pair of opposite
5 min read
Convex Hull | Monotone chain algorithm
Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) Examples: Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: (0, 0) (3, 0)
12 min read
Perimeter of Convex hull for a given set of points
Given n 2-D points points[], the task is to find the perimeter of the convex hull for the set of points. A convex hull for a set of points is the smallest convex polygon that contains all the points. Examples: Input: points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: 12 Input: points[] = {{0, 2}, {2, 1}, {3, 1}, {3, 7}} Out
10 min read
Check if the given point lies inside given N points of a Convex Polygon
Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples: Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2 Below is the image of plotting of the given points: Output: YES Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4
15 min read
Deleting points from Convex Hull
Given a fixed set of points. We need to find convex hull of given set. We also need to find convex hull when a point is removed from the set. Example: Initial Set of Points: (-2, 8) (-1, 2) (0, 1) (1, 0) (-3, 0) (-1, -9) (2, -6) (3, 0) (5, 3) (2, 5) Initial convex hull:- (-2, 8) (-3, 0) (-1, -9) (2, -6) (5, 3)Point to remove from the set : (-2, 8)F
15+ min read
Quickhull Algorithm for Convex Hull
Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not PossibleThere must be at least three points to form
14 min read
Convex Hull using Jarvis' Algorithm or Wrapping
Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it. We strongly recommend to see the following post first. How to check if two given line segments intersect?The idea of Jarvis's Algorithm is simple, we start from the leftmost point (or point with minimum x coordinate valu
14 min read
Convex Hull using Divide and Conquer Algorithm
In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computational geometry for several reasons: Collision detectio
15 min read
Convex Hull in Python
The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling. What is Convex Hull?The convex h
15+ min read
Quickhull for Convex hull in Python
Quickhull is an efficient algorithm used to find the convex hull of a set of points in a plane. It works by recursively dividing the point set into two subsets and finding the convex hull for each subset. Quickhull Algorithm for Convex hull:Base Case:If the set of points has 0 or 1 elements, it is already the convex hull.Find the Endpoints:Find the
3 min read
Check if given polygon is a convex polygon or not
Given a 2D array point[][] with each row of the form {X, Y}, representing the co-ordinates of a polygon in either clockwise or counterclockwise sequence, the task is to check if the polygon is a convex polygon or not. If found to be true, then print "Yes" . Otherwise, print "No". In a convex polygon, all interior angles are less than or equal to 18
9 min read
Convex Hull Algorithm
The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling. What is Convex Hull?The convex h
8 min read
Find number of diagonals in n sided convex polygon
Given n &gt; 3, find number of diagonals in n sided convex polygon.According to Wikipedia, In geometry, a diagonal is a line segment joining two vertices of a polygon or polyhedron, when those vertices are not on the same edge. Informally, any sloping line is called diagonal. Examples :  Input : 5Output : 5Explanation: Five possible diagonals are :
3 min read
Convex Hull using Graham Scan
Prerequisite: How to check if two given line segments intersect?Jarvis’s Algorithm A convex hull is the smallest convex polygon that contains a given set of points. It is a useful concept in computational geometry and has applications in various fields such as computer graphics, image processing, and collision detection. A convex polygon is a polyg
15+ min read
Ways to paint stairs with two colors such that two adjacent are not yellow
Given n stairs and we have 2 colour yellow and green the task is that we have to paint given stairs by given colour with condition is that we cannot paints two yellow steps directly after each other.Examples : Input : n = 1 Output : 2 A single stair can be colored either as green or yellow. Input : n = 3 Output : 5 Case 1: When we have 1 stair, we
4 min read
Find area of triangle if two vectors of two adjacent sides are given
Given two vectors in form of (xi+yj+zk) of two adjacent sides of a triangle. The task is to find out the area of a triangle.Examples: Input: x1 = -2, y1 = 0, z1 = -5 x2 = 1, y2 = -2, z2 = -1 Output: Area = 6.422616289332565Input: x1 = -2, y1 = 1, z1 = 5 x2 = 1, y2 = 3, z2 = -1 Output: Area = 8.860022573334675 Approach: Suppose we have two vectors a
5 min read
Ways of dividing a group into two halves such that two elements are in different groups
Given 2n girls and randomly divided into two subgroups each containing n girls. The task is to count the number of ways in which groups can be formed such that two beautiful girls are into different groups.Example: Input: 4 Output: 4 Let group be r1, r2, b1, b2 where b1 and b2 are beautiful girls Groups are: ((r1, b1) (r2, b2)), ((r1, b2) (r2, b1))
6 min read
Probability of getting two consecutive heads after choosing a random coin among two different types of coins
Given two coins which have probability of getting heads p% and q% respectively, the task is to determine the probability of getting two consecutive heads after choosing random coins among the given coins.Examples: Input: p = 33, q = 66 Output: 0.550000000000000Input: p = 33, q = 66 Output: 0.550000000000000 Approach: Since both the coins are not id
5 min read
Add two integers of different base and represent sum in smaller base of the two
Given two integers X, Y in base B1 and B2 respectively, the task is to find the sum of integers X and Y and represent the result in min of ( B1 and B2 ). Example: Input: X = 123, Y = 234, B1 = 6, B2 = 8 Output: 543 Explanation: Integer in base 10: 51 and 156 Sum of Integers: 207 Minimum Base: 6 Sum of Integer in Base 6 = 543 Input: X = 16, Y = 24,
15+ min read