Number of Triangles that can be formed given a set of lines in Euclidean Plane
Last Updated : 23 Jun, 2022
Given a set L = {l1, l2, ……..., ln} of ‘n’ distinct lines on the Euclidean Plane. The ith line is given by an equation in the form aix + biy = ci. Find the number of triangles that can be formed using the lines in the set L. Note that no two pairs of lines intersect at the same point.
Note: This problem doesn’t mention that the lines can’t be parallel which makes the problem difficult to solve.
Examples:
Input: a[] = {1, 2, 3, 4} b[] = {2, 4, 5, 5} c[] = {5, 7, 8, 6} Output: 2 The number of triangles that can be formed are: 2 Input: a[] = {1, 2, 3, 2, 4, 1, 2, 3, 4, 5} b[] = {2, 4, 6, 3, 6, 5, 10, 15, 20, 25} c[] = {3, 5, 11, 10, 9, 17, 13, 11, 7, 3} Output: 30 The number of triangles that can be formed are: 30
Naive Algorithm
The naive algorithm can be described as:
- Pick up 3 arbitrary lines from the set L.
- Now check if a triangle can be formed using the selected 3 lines. This can be done easily by checking that none of them is pairwise parallel.
- Increment the counter if the triangle can be formed.
Time Complexity: There are nC3 triplets of lines. For each triplet, we have to do 3 comparisons to check that any 2 lines are not parallel which means the check can be done in O(1) time. This makes the naive algorithm O(n3).
Efficient Algorithm
This can also be achieved in O(n log n). The logic behind the efficient algorithm is described below.
We divide the set L in various subsets. The formation of subsets is based on slopes i.e. all the lines in a particular subset have the same slope i.e. they are parallel to each other.
Let us consider three sets (say A, B and C). For a particular set (say A) the lines belonging to this are all parallel to each other. If we have A, B, and C, we can pick one line from each set to get a triangle because none of these lines will be parallel. By making the subsets we have ensured that no two lines which are parallel are being picked together.

Now if we have only these 3 subsets,
Number of triangles = (Number of ways to pick a line from A) * (Number of ways to pick a line from B) * (Number of ways to pick a line from C) = m1*m2*m3 Here m1 is count of elements with first slope (in Set A) Here m2 is count of elements with first slope (in Set B) Here m3 is count of elements with first slope (in Set C)
Similarly, if we have 4 subsets, we can extend this logic to get,
Number of triangles = m1*m2*m3 + m1*m2*m4 + m1*m3*m4 + m2*m3*m4
For number of subsets greater than 3, If we have ‘k’ subsets, our task is to find the sum of number of elements of the subset taken 3 at a time. This can be done by maintaining a count array. We make a count array where counti denotes the count of the ith subset of parallel lines.
We one by one compute following values. sum1 = m1 + m2 + m3 ..... sum2 = m1*m2 + m1*m3 + ... + m2*m3 + m2*m4 + ... sum3 = m1*m2*m3 + m1*m2*m4 + ...... m2*m3*m4 + .... sum3 gives our final answer
C++ // C++ program to find the number of // triangles that can be formed // using a set of lines in Euclidean // Plane #include <bits/stdc++.h> using namespace std; #define EPSILON numeric_limits<double>::epsilon() // double variables can't be checked precisely // using '==' this function returns true if // the double variables are equal bool compareDoubles(double A, double B) { double diff = A-B; return (diff<EPSILON) && (-diff<EPSILON); } // This function returns the number of triangles // for a given set of lines int numberOfTringles(int a[], int b[], int c[], int n) { //slope array stores the slope of lines double slope[n]; for (int i=0; i<n; i++) slope[i] = (a[i]*1.0)/b[i]; // slope array is sorted so that all lines // with same slope come together sort(slope, slope+n); // After sorting slopes, count different // slopes. k is index in count[]. int count[n], k = 0; int this_count = 1; // Count of current slope for (int i=1; i<n; i++) { if (compareDoubles(slope[i], slope[i-1])) this_count++; else { count[k++] = this_count; this_count = 1; } } count[k++] = this_count; // calculating sum1 (Sum of all slopes) // sum1 = m1 + m2 + ... int sum1 = 0; for (int i=0; i<k; i++) sum1 += count[i]; // calculating sum2. sum2 = m1*m2 + m2*m3 + ... int sum2 = 0; int temp[n]; // Needed for sum3 for (int i=0; i<k; i++) { temp[i] = count[i]*(sum1-count[i]); sum2 += temp[i]; } sum2 /= 2; // calculating sum3 which gives the final answer // m1 * m2 * m3 + m2 * m3 * m4 + ... int sum3 = 0; for (int i=0; i<k; i++) sum3 += count[i]*(sum2-temp[i]); sum3 /= 3; return sum3; } // Driver code int main() { // lines are stored as arrays of a, b // and c for 'ax+by=c' int a[] = {1, 2, 3, 4}; int b[] = {2, 4, 5, 5}; int c[] = {5, 7, 8, 6}; // n is the number of lines int n = sizeof(a)/sizeof(a[0]); cout << "The number of triangles that" " can be formed are: " << numberOfTringles(a, b, c, n); return 0; }
Java // Java program to find the number of // triangles that can be formed // using a set of lines in Euclidean // Plane import java.util.*; class GFG{ static double EPSILON = 1.0842e-19; // Double variables can't be checked precisely // using '==' this function returns true if // the double variables are equal static boolean compareDoubles(double A, double B) { double diff = A - B; return (diff < EPSILON) && (-diff < EPSILON); } // This function returns the number of // triangles for a given set of lines static int numberOfTringles(int []a, int []b, int []c, int n) { // Slope array stores the slope of lines Vector<Double> slope = new Vector<>(); for(int i = 0; i < n; i++) slope.add((double)(a[i] * 1.0) / b[i]); // Slope array is sorted so that all lines // with same slope come together Collections.sort(slope); // After sorting slopes, count different // slopes. k is index in count[]. int []count = new int [n]; int k = 0; // Count of current slope int this_count = 1; for(int i = 1; i < n; i++) { if (compareDoubles((double)slope.get(i), (double)slope.get(i - 1))) this_count++; else { count[k++] = this_count; this_count = 1; } } count[k++] = this_count; // Calculating sum1 (Sum of all slopes) // sum1 = m1 + m2 + ... int sum1 = 0; for(int i = 0; i < k; i++) sum1 += count[i]; // Calculating sum2. sum2 = m1*m2 + m2*m3 + ... int sum2 = 0; // Needed for sum3 int temp[] = new int [n]; for(int i = 0; i < k; i++) { temp[i] = count[i] * (sum1 - count[i]); sum2 += temp[i]; } sum2 /= 2; // Calculating sum3 which gives the // final answer // m1 * m2 * m3 + m2 * m3 * m4 + ... int sum3 = 0; for(int i = 0; i < k; i++) sum3 += count[i] * (sum2 - temp[i]); sum3 /= 3; return sum3; } // Driver code public static void main(String[] args) { // Lines are stored as arrays of a, b // and c for 'ax+by=c' int a[] = { 1, 2, 3, 4 }; int b[] = { 2, 4, 5, 5 }; int c[] = { 5, 7, 8, 6 }; // n is the number of lines int n = a.length; System.out.println("The number of triangles " + "that can be formed are: " + numberOfTringles(a, b, c, n)); } } // This code is contributed by Stream_Cipher
Python3 # Python program to find the number of # triangles that can be formed # using a set of lines in Euclidean # Plane import math EPSILON = 1.0842e-19 # double variables can't be checked precisely # using '==' this function returns true if # the double variables are equal def compareDoubles(A, B): diff = A-B return (diff < EPSILON) and (-diff < EPSILON) # This function returns the number of triangles # for a given set of lines def numberOfTringles(a, b, c, n): # slope array stores the slope of lines slope = [] for i in range(0, n): slope.append((a[i]*1.0)/b[i]) # slope array is sorted so that all lines # with same slope come together slope.sort() # After sorting slopes, count different # slopes. k is index in count[]. k = 0 count = [] this_count = 1 # Count of current slope for i in range(1, n): if compareDoubles(slope[i], slope[i-1]): this_count = this_count + 1 else: count.append(this_count) k = k + 1 this_count = 1 count.append(this_count) k = k + 1 # calculating sum1 (Sum of all slopes) # sum1 = m1 + m2 + ... sum1 = 0 for i in range(0, k): sum1 += count[i] # calculating sum2. sum2 = m1*m2 + m2*m3 + ... sum2 = 0 temp = [] # Needed for sum3 for i in range(0, k): temp.append(count[i]*(sum1-count[i])) sum2 += temp[i] sum2 = math.floor(sum2/2) # calculating sum3 which gives the final answer # m1 * m2 * m3 + m2 * m3 * m4 + ... sum3 = 0 for i in range(0, k): sum3 += count[i]*(sum2-temp[i]) sum3 = math.floor(sum3/3) return sum3 # Driver Code # lines are stored as arrays of a, b # and c for 'ax+by=c' a = [1, 2, 3, 4] b = [2, 4, 5, 5] c = [5, 7, 8, 6] # n is the number of lines n = len(a) print("The number of triangles that can be formed are: ", numberOfTringles(a, b, c, n)) # The code is contributed by Gautam goel (gautamgoel962)
C# // C# program to find the number of // triangles that can be formed // using a set of lines in Euclidean // Plane using System.Collections.Generic; using System; class GFG{ static double EPSILON = 1.0842e-19; // Double variables can't be checked precisely // using '==' this function returns true if // the double variables are equal static bool compareDoubles(double A, double B) { double diff = A - B; return (diff < EPSILON) && (-diff < EPSILON); } // This function returns the number of // triangles for a given set of lines static int numberOfTringles(int []a, int []b, int []c, int n) { // Slope array stores the slope of lines List<double> slope = new List<double>(); for(int i = 0; i < n; i++) slope.Add((double)(a[i] * 1.0) / b[i]); // Slope array is sorted so that all lines // with same slope come together slope.Sort(); // After sorting slopes, count different // slopes. k is index in count[]. int []count = new int [n]; int k = 0; // Count of current slope int this_count = 1; for(int i = 1; i < n; i++) { if (compareDoubles((double)slope[i], (double)slope[i - 1])) this_count++; else { count[k++] = this_count; this_count = 1; } } count[k++] = this_count; // Calculating sum1 (Sum of all slopes) // sum1 = m1 + m2 + ... int sum1 = 0; for(int i = 0; i < k; i++) sum1 += count[i]; // Calculating sum2. sum2 = m1*m2 + m2*m3 + ... int sum2 = 0; // Needed for sum3 int []temp = new int [n]; for(int i = 0; i < k; i++) { temp[i] = count[i] * (sum1 - count[i]); sum2 += temp[i]; } sum2 /= 2; // Calculating sum3 which gives // the final answer // m1 * m2 * m3 + m2 * m3 * m4 + ... int sum3 = 0; for(int i = 0; i < k; i++) sum3 += count[i] * (sum2 - temp[i]); sum3 /= 3; return sum3; } // Driver code public static void Main() { // lines are stored as arrays of a, b // and c for 'ax+by=c' int []a = { 1, 2, 3, 4 }; int []b = { 2, 4, 5, 5 }; int []c = { 5, 7, 8, 6 }; // n is the number of lines int n = a.Length; Console.WriteLine("The number of triangles " + "that can be formed are: " + numberOfTringles(a, b, c, n)); } } // This code is contributed by Stream_Cipher
JavaScript <script> // JavaScript program to find the number of // triangles that can be formed // using a set of lines in Euclidean // Plane const EPSILON = 1.0842e-19; // Double variables can't be checked precisely // using '==' this function returns true if // the double variables are equal function compareDoubles(A, B) { var diff = A - B; return diff < EPSILON && -diff < EPSILON; } // This function returns the number of // triangles for a given set of lines function numberOfTringles(a, b, c, n) { // Slope array stores the slope of lines var slope = []; for (var i = 0; i < n; i++) slope.push(parseFloat(a[i] * 1.0) / b[i]); // Slope array is sorted so that all lines // with same slope come together slope.sort(); // After sorting slopes, count different // slopes. k is index in count[]. var count = new Array(n).fill(0); var k = 0; // Count of current slope var this_count = 1; for (var i = 1; i < n; i++) { if (compareDoubles(parseFloat(slope[i]), parseFloat(slope[i - 1]))) this_count++; else { count[k++] = this_count; this_count = 1; } } count[k++] = this_count; // Calculating sum1 (Sum of all slopes) // sum1 = m1 + m2 + ... var sum1 = 0; for (var i = 0; i < k; i++) sum1 += count[i]; // Calculating sum2. sum2 = m1*m2 + m2*m3 + ... var sum2 = 0; // Needed for sum3 var temp = new Array(n).fill(0); for (var i = 0; i < k; i++) { temp[i] = count[i] * (sum1 - count[i]); sum2 += temp[i]; } sum2 /= 2; // Calculating sum3 which gives // the final answer // m1 * m2 * m3 + m2 * m3 * m4 + ... var sum3 = 0; for (var i = 0; i < k; i++) sum3 += count[i] * (sum2 - temp[i]); sum3 /= 3; return sum3; } // Driver code // lines are stored as arrays of a, b // and c for 'ax+by=c' var a = [1, 2, 3, 4]; var b = [2, 4, 5, 5]; var c = [5, 7, 8, 6]; // n is the number of lines var n = a.length; document.write( "The number of triangles " + "that can be formed are: " + numberOfTringles(a, b, c, n) ); // This code is contributed by rdtank. </script>
Output:
The number of triangles that can be formed are: 2
Time Complexity: All the loops in the code are O(n). The time complexity in this implementation is thus driven by the sort function used to sort the slope array. This makes the algorithm O(nlogn).
Auxiliary Space: O(n)
Similar Reads
Geometric Algorithms Geometric algorithms are a type of algorithm that deal with solving problems related to geometry. These algorithms are used to solve various geometric problems such as computing the area of a polygon, finding the intersection of geometric shapes, determining the convex hull of a set of points, and m
4 min read
Problems based on Pattern Printing
Print lower triangle with alternate '*' and '#'Given a number N which denotes the number of rows, the task is to follow the below pattern to print the first N rows of it. Pattern: **#*#**#*#*#*#* Examples: Input: N = 2Output:**# Input: N = 6Output: **#*#**#*#*#*#**#*#*# Approach: Follow the below steps to implement the above pattern: Initialize
4 min read
Print the pattern 1*2*5*6 --3*4Given integer N, the task is to print an upside-down triangle where the left half is made of elements in the range [1, N*(N+1)/2] and the right half is made of elements in the range [N*(N+1)/2 + 1, N*(N+1)]. Examples: Input: N = 3 Output: 1*2*3*10*11*12 4*5*8*9 6*7 Input: n = 4Output:1*2*3*4*17*18*1
6 min read
Python Program to print the pattern 'G'In this article, we will learn how to print the pattern G using stars and white-spaces. Given a number n, we will write a program to print the pattern G over n lines or rows.Examples: Input : 7Output : *** * * * *** * * * * *** Input : 9Output : ***** * * * * *** * * * * * * ***** In this program, w
2 min read
Program to Print Pascal's TriangleGiven an integer n, the task is to find the first n rows of Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients.Examples: Example1: The below image shows the Pascal's Triangle for n=4 Example2: The below image shows the Pascal's Triangle for n = 6 Table of Content[Nai
15 min read
Program to print pyramid patternWrite to program to print the pyramid pattern formed of stars Example : Input: n = 6 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two for loops for every part of the p
5 min read
Program to print the Diamond ShapeGiven a number n, write a program to print a diamond shape with 2n rows.Examples : C++ // C++ program to print diamond shape // with 2n rows #include <bits/stdc++.h> using namespace std; // Prints diamond pattern with 2n rows void printDiamond(int n) { int space = n - 1; // run loop (parent lo
11 min read
Hour-glass PatternGiven positive integer n, print numeric pattern in form of an hourglass.Examples : Input : rows_no = 7 Output : 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 C++ // CPP code for hour glass // pattern. #include <iostream> using nam
7 min read
Program to print V and inverted-V patternInverted V pattern: Given the value of n, print the inverted V pattern.Examples : Input : n = 5 Output : E D D C C B B A A Input : n = 7 Output : G F F E E D D C C B B A A Below is the program to print the above pattern C++ // C++ Implementation to print the pattern #include <bits/stdc++.h> us
8 min read
Program to print hollow pyramid, diamond pattern and their modificationsFor Prerequisite : Loops, If Else Statement1. Hollow pyramid/triangle pattern The pattern is similar to pyramid pattern. The only difference is, we will replace all internal '#' or '*' characters by space character and we will print 2*N-1 (N = number of rows in pattern) '#' or '*' characters in last
15+ min read
Code to Generate the Map of India (With Explanation)Given an obfuscated code that generates the map of India, explain its working. The following code when executed generates the map of India. An obfuscated code is a code that has been deliberately made difficult to understand or difficult to read, typically for the purpose of hiding its logic or maki
8 min read
Problems based on Lines
How to check if two given line segments intersect?Given two line segments represented as a 3D vector points[][][], where each line segment i is defined by its endpoints stored in points[i][0] and points[i][1] (each containing 2 integers), your task is to determine if these two line segments intersect with each other.Examples:Input: points[][][] = [
10 min read
Sweep Line Algorithm - Find if any Two Segments IntersectGiven n line segments represented as a 3D vector points[][][], where each line segment i is defined by its endpoints stored in points[i][0] and points[i][1] (each containing 2 integers), your task is to determine if any two of these line segments intersect and find the number of intersection points.
15+ min read
Klee's Algorithm (Length Of Union Of Segments of a line)Given starting and ending positions of segments on a line, the task is to take the union of all given segments and find length covered by these segments.Examples: Input : segments[] = {{2, 5}, {4, 8}, {9, 12}} Output : 9 Explanation: segment 1 = {2, 5} segment 2 = {4, 8} segment 3 = {9, 12} If we ta
9 min read
Count maximum points on same lineGiven N point on a 2D plane as pair of (x, y) co-ordinates, we need to find maximum number of point which lie on the same line. Examples: Input : points[] = {-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4} Output : 4 Then maximum number of point which lie on same line are 4, those point are {0, 0}, {
10 min read
Minimum lines to cover all pointsGiven N points in 2-dimensional space, we need to print the count of the minimum number of lines which traverse through all these N points and which go through a specific (xO, yO) point also.Examples: If given points are (-1, 3), (4, 3), (2, 1), (-1, -2), (3, -3) and (xO, yO) point is (1, 0) i.e. ev
9 min read
Represent a given set of points by the best possible straight lineFind the value of m and c such that a straight line y = mx + c, best represents the equation of a given set of points (x_1 , y_1 ), (x_2 , y_2 ), (x_3 , y_3 ), ......., (x_n , y_n ), given n >=2. Examples: Input : n = 5 x_1 = 1, x_2 = 2, x_3 = 3, x_4 = 4, x_5 = 5y_1 = 14, y_2 = 27, y_3 = 40, y_4
10 min read
Program to find line passing through 2 PointsGiven two points P and Q in the coordinate plane, find the equation of the line passing through both points.This kind of conversion is very useful in many geometric algorithms like intersection of lines, finding the circumcenter of a triangle, finding the incenter of a triangle and many more... Exam
6 min read
Reflection of a point about a line in C++Letâs first consider a general case where the line is nothing but the X-Axis. We can now definitely say that the conjugate of a point is the reflection of the point about X-Axis.Now, using the methods of translation and rotation of coordinate axes we will find out the reflection of a point about the
4 min read
Program to find the mid-point of a lineGiven two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : Input : x1 = â1, y1 = 2, x2 = 3, y2 = â6 Output : 1,â2 Input : x1 = 6.4, y1 = 3 x2 = â10.7, y2 = 4 Output : â2.15, 3.5 The Midpoint Formula: The midpoint of two points, (x1, y2) and
3 min read
Sum of Manhattan distances between all pairs of pointsGiven n integer coordinates. The task is to find the sum of the Manhattan distance between all pairs of coordinates. Manhattan Distance between (x1, y1) and (x2, y2) is: |x1 - x2| + |y1 - y2|Examples : Input : n = 4, p1 = { -1, 5 }, p2 = { 1, 6 }, p3 = { 3, 5 }, p4 = { 2, 3 }Output : 22Explanation :
9 min read
Program to check if three points are collinearGiven three points, check whether they lie on a straight (collinear) or notExamples : Input : (1, 1), (1, 4), (1, 5) Output : Yes The points lie on a straight line Input : (1, 5), (2, 5), (4, 6) Output : No The points do not lie on a straight line First approach Three points lie on the straight line
9 min read
Problems based on Triangles
Check whether a given point lies inside a triangle or notGiven 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: InsideExplanation: B(10,30) / \ / \ / \ / P \ P' / \ A(0,0) ----------- C(20,0) Input: A = (0, 0
15+ min read
Program to find area of a triangleGiven the sides of a triangle, the task is to find the area of this triangle. Examples : Input : a = 5, b = 7, c = 8 Output : Area of a triangle is 17.320508 Input : a = 3, b = 4, c = 5 Output : Area of a triangle is 6.000000Recommended PracticeArea of a triangleTry It! Approach: The area of a trian
10 min read
Count Integral points inside a TriangleGiven three non-collinear integral points in XY plane, find the number of integral points inside the triangle formed by the three points. (A point in XY plane is said to be integral/lattice point if both its co-ordinates are integral). Example: Input: p = (0, 0), q = (0, 5) and r = (5,0) Output: 6Ex
8 min read
Maximum number of 2x2 squares that can be fit inside a right isosceles triangleWhat is the maximum number of squares of size 2x2 units that can be fit in a right-angled isosceles triangle of a given base (in units). A side of the square must be parallel to the base of the triangle. Examples: Input : 8Output : 6Explanation: We get total 6 squares ( 1 + 2 + 3). Please refer the
3 min read
Find all angles of a given triangleGiven coordinates of all three vertices of the triangle in the 2D plane, the task is to find all three angles.Example: Input : A = (0, 0), B = (0, 1), C = (1, 0) Output : 90, 45, 45 To solve this problem we use below Law of cosines. c^2 = a^2 + b^2 - 2(a)(b)(cos beta) After re-arranging beta = acos(
7 min read
Check if right triangle possible from given area and hypotenuseGiven area and hypotenuse, the aim is to print all sides if right triangle can exist, else print -1. We need to print all sides in ascending order. Examples: Input : 6 5 Output : 3 4 5 Input : 10 6 Output : -1 We have discussed a solution of this problem in below post. Find all sides of a right angl
6 min read
Number of Triangles that can be formed given a set of lines in Euclidean PlaneGiven a set L = {l1, l2, â¦â¦..., ln} of ânâ distinct lines on the Euclidean Plane. The ith line is given by an equation in the form aix + biy = ci. Find the number of triangles that can be formed using the lines in the set L. Note that no two pairs of lines intersect at the same point. Note: This pro
13 min read
Program to calculate area of Circumcircle of an Equilateral TriangleGiven the length of sides of an equilateral triangle. We need to write a program to find the area of Circumcircle of the given equilateral triangle.Examples: Input : side = 6 Output : Area of circumscribed circle is: 37.69 Input : side = 9 Output : Area of circumscribed circle is: 84.82 All three si
4 min read
Program to calculate area and perimeter of equilateral triangleAn equilateral triangle is a triangle in which all three sides and angles are equal. All three internal angles of equilateral triangle measures 60 degree. If we know the length of each sides of equilateral triangle, then we can use below mentioned formula to calculate area of equilateral triangle.Ar
4 min read
Minimum height of a triangle with given base and areaGiven two integers a and b, find the smallest possible height such that a triangle of at least area "a" and base "b" can be formed.Examples:Â Input : a = 2, b = 2Output : Minimum height of triangle is 2Explanation: Input : a = 8, b = 4Output : Minimum height of triangle is 4Minimum height of Triangle
5 min read
Problems based on Rectangle, Square and Circle
Find if two rectangles overlapGiven two rectangles, find if the given two rectangles overlap or not.Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates. l1: Top Left coordinate of first rectangle. r1: Bottom Right coordinate of first rectangle.
5 min read
Check if four segments form a rectangleWe are given four segments as a pair of coordinates of their end points. We need to tell whether those four line segments make a rectangle or not. Examples: Input : segments[] = [(4, 2), (7, 5), (2, 4), (4, 2), (2, 4), (5, 7), (5, 7), (7, 5)] Output : Yes Given these segment make a rectangle of leng
9 min read
Minimum Perimeter of n blocksWe are given n blocks of size 1 x 1, we need to find the minimum perimeter of the grid made by these blocks.Examples : Input : n = 4Output : 8Minimum possible perimeter with 4 blocksis 8. See below explanation.Input : n = 11Output : 14The square grid of above examples would be as Let us take an exam
5 min read
Number of rectangles in N*M gridWe are given a N*M grid, print the number of rectangles in it.Examples: Input : N = 2, M = 2Output : 9There are 4 rectangles of size 1 x 1.There are 2 rectangles of size 1 x 2There are 2 rectangles of size 2 x 1There is one rectangle of size 2 x 2.Input : N = 5, M = 4Output : 150Input : N = 4, M = 3
7 min read
Coordinates of rectangle with given points lie insideGiven two arrays X[] and Y[] with n-elements, where (Xi, Yi) represent a point on coordinate system, find the smallest rectangle such that all points from given input lie inside that rectangle and sides of rectangle must be parallel to Coordinate axis. Print all four coordinates of an obtained recta
6 min read
Program for Area Of SquareA square is a flat shape, in one plane, defined by four points at the four corners. A square has four sides all of equal length, and four corners, all right angles (90 degree angles). A square is a kind of rectangle. Examples : Input : 4 Output :16 Input :8 Output :64 Formula Area = side*side C++ //
2 min read
Circle and Lattice PointsGiven a circle of radius r in 2-D with origin or (0, 0) as center. The task is to find the total lattice points on circumference. Lattice Points are points with coordinates as integers in 2-D space.Example: Input : r = 5.Output : 12Below are lattice points on a circle withradius 5 and origin as (0,
6 min read
Pizza cut problem (Or Circle Division by Lines)Given number of cuts, find the maximum number of possible pieces.Examples: Input : 2 Output : 4 Input : 3 Output : 7 This problem is nothing but The Lazy Catererâs Problem and has below formula.Maximum number of pieces = 1 + n*(n+1)/2Refer this for proof. C++ // C++ program to find maximum no of pie
2 min read
Angular Sweep (Maximum points that can be enclosed in a circle of given radius)Given ânâ points on the 2-D plane, find the maximum number of points that can be enclosed by a fixed-radius circle of radius âRâ. Note: The point is considered to be inside the circle even when it lies on the circumference. Examples: Input: R = 1 points[] = {(6.47634, 7.69628), (5.16828 4.79915), (
15 min read
Check if a line touches or intersects a circleGiven coordinate of the center and radius > 1 of a circle and the equation of a line. The task is to check if the given line collides with the circle or not. There are three possibilities : Line intersects the circle.Line touches the circle.Line is outside the circle Note: General equation of a l
6 min read
Area of a Circumscribed Circle of a SquareGiven the side of a square then find the area of a Circumscribed circle around it.Examples: Input : a = 6 Output : Area of a circumscribed circle is : 56.55 Input : a = 4 Output : Area of a circumscribed circle is : 25.13 All four sides of a square are of equal length and all four angles are 90 degr
3 min read
Area of square Circumscribed by CircleGiven the radius(r) of circle then find the area of square which is Circumscribed by circle.Examples: Input : r = 3Output :Area of square = 18Input :r = 6Output :Area of square = 72 All four sides of a square are of equal length and all four angles are 90 degree. The circle is circumscribed on a giv
4 min read
Program to find area of a Circular SegmentIn a circle, if a chord is drawn then that chord divides the whole circle into two parts. These two parts of the circle are called segments of the circle. The smaller area is known as the Minor segment and the larger area is called as the Major segment.In the figure below, the chord AB divides the c
6 min read
Arc length from given AngleAn angle is a geometrical figure when two rays meet at a common point on a plane. These rays form the sides of the angle and the meeting point is referred as the vertex of the angle. There is something that we need to keep in mind that the plane that forms an angle doesn't need to be a Euclidean pla
4 min read
Program to find Circumference of a CircleGiven radius of a circle, write a program to find its circumference.Examples : Input : 2 Output : Circumference = 12.566 Input : 8 Output : Circumference = 50.264 In a circle, points lie in the boundary of a circle are at same distance from its center. This distance is called radius. Circumference o
3 min read
Check if two given circles touch or intersect each otherThere are two circles A and B with their centres C1(x1, y1) and C2(x2, y2) and radius R1 and R2. The task is to check both circles A and B touch each other or not. Examples : Input : C1 = (3, 4) C2 = (14, 18) R1 = 5, R2 = 8Output : Circles do not touch each other. Input : C1 = (2, 3) C2 = (15, 28) R
5 min read
Problems based on 3D Objects
Find the perimeter of a cylinderGiven diameter and height, find the perimeter of a cylinder.Perimeter is the length of the outline of a two - dimensional shape. A cylinder is a three - dimensional shape. So, technically we cannot find the perimeter of a cylinder but we can find the perimeter of the cross-section of the cylinder. T
3 min read
Find the Surface area of a 3D figureGiven a N*M matrix A[][] representing a 3D figure. The height of the building at (i, j) is A[i][j] . Find the surface area of the figure. Examples : Input : N = 1, M = 1 A[][] = { {1} } Output : 6 Explanation : The total surface area is 6 i.e 6 side of the figure and each are of height 1. Input : N
11 min read
Calculate Volume of DodecahedronGiven the edge of the dodecahedron calculate its Volume. Volume is the amount of the space which the shapes takes up. A dodecahedron is a 3-dimensional figure made up of 12 faces, or flat sides. All of the faces are pentagons of the same size.The word 'dodecahedron' comes from the Greek words dodeca
3 min read
Program to calculate volume of OctahedronGiven the side of the Octahedron then calculate the volume of Octahedron. Examples: Input : 3 Output : 12.7279 Input : 7 Output : 161.692 Approach: The volume of an octahedron is given by the formula: Volume = â2/3 Ã a3 where a is the side of Octahedron Below is the implementation to calculate volum
2 min read
Program to calculate Volume and Surface area of HemisphereCalculate volume and surface area of a hemisphere. Hemisphere : In geometry, it is an exact half of a sphere. We can find many of the real life examples of the hemispheres such as our planet Earth can be divided into two hemisphere the southern & northern hemispheres.  Volume of Hemisphere : Vo
4 min read
Program for volume of PyramidA pyramid is a 3-dimensional geometric shape formed by connecting all the corners of a polygon to a central apex. There are many types of pyramids. Most often, they are named after the type of base they have. Let's look at some common types of pyramids below. Volume of a square pyramid [base of Pyra
7 min read
Program to calculate volume of EllipsoidEllipsoid, closed surface of which all plane cross sections are either ellipses or circles. An ellipsoid is symmetrical about three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape, all planar sections of which are ellipses or circles. An el
4 min read
Program for Volume and Surface Area of CubeCube is a 3-dimensional box-like figure represented in the 3-dimensional plane. Cube has 6 squared-shape equal faces. Each face meet another face at 90 degree each. Three sides of cube meet at same vertex. Examples: Input : Side of a cube = 2 Output : Area = 8 Total surface area = 24 Input : Side of
3 min read
Problems based on Quadrilateral
Number of parallelograms when n horizontal parallel lines intersect m vertical parallel linesGiven two positive integers n and m. The task is to count number of parallelogram that can be formed of any size when n horizontal parallel lines intersect with m vertical parallel lines. Examples: Input : n = 3, m = 2Output : 32 parallelograms of size 1x1 and 1 parallelogram of size 2x1.Input : n =
8 min read
Program for Circumference of a ParallelogramGiven the sides of Parallelogram then calculate the circumference.Examples : Input: a = 10, b = 8 Output: 36.00 Input: a = 25.12, b = 20.4 Output: 91.04 The opposite sides of a parallelogram are of equal length and parallel. The angles are pairwise equal but not necessarily 90 degree. The circumfere
3 min read
Program to calculate area and perimeter of TrapeziumA trapezium is a quadrilateral with at least one pair of parallel sides, other two sides may not be parallel. The parallel sides are called the bases of the trapezium and the other two sides are called it's legs. The perpendicular distance between parallel sides is called height of trapezium. Formul
5 min read
Program to find area of a TrapezoidDefinition of Trapezoid : A Trapezoid is a convex quadrilateral with at least one pair of parallel sides. The parallel sides are called the bases of the trapezoid and the other two sides which are not parallel are referred to as the legs. There can also be two pairs of bases. In the above figure CD
4 min read
Find all possible coordinates of parallelogramFind all the possible coordinates from the three coordinates to make a parallelogram of a non-zero area.Let's call A, B, and C are the three given points. We can have only the three possible situations:Â (1) AB and AC are sides, and BC a diagonal(2) AB and BC are sides, and AC a diagonal (3) BC and
5 min read
Maximum area of quadrilateralGiven four sides of quadrilateral a, b, c, d, find the maximum area of the quadrilateral possible from the given sides .Examples:  Input : 1 2 1 2Output : 2.00It is optimal to construct a rectangle for maximum area .  According to Bretschneider's formula, the area of a general quadrilateral is given
5 min read
Check whether four points make a parallelogramGiven four points in a 2-dimensional space we need to find out whether they make a parallelogram or not. A parallelogram has four sides. Two opposite sides are parallel and are of same lengths. Examples:Points = [(0, 0), (4, 0), (1, 3), (5, 3)]Above points make a parallelogram.Points = [(0, 0), (2,
15+ min read
Find the Missing Point of ParallelogramGiven three coordinate points A, B and C, find the missing point D such that ABCD can be a parallelogram.Examples : Input : A = (1, 0) B = (1, 1) C = (0, 1) Output : 0, 0 Explanation: The three input points form a unit square with the point (0, 0) Input : A = (5, 0) B = (1, 1) C = (2, 5) Output : 6,
13 min read
Problems based on Polygon and Convex Hull
How to check if a given point lies inside or outside a polygon?Given a polygon and a point 'p', find if 'p' lies inside the polygon or not. The points lying on the border are considered inside. Examples: Recommended ProblemPlease solve it on PRACTICE first, before moving on to the solution Solve ProblemApproach: The idea to solve this problem is based on How to
9 min read
Area of a polygon with given n ordered verticesGiven ordered coordinates of a polygon with n vertices. Find the area of the polygon. Here ordered means that the coordinates are given either in a clockwise manner or anticlockwise from the first vertex to last.Examples : Input : X[] = {0, 4, 4, 0}, Y[] = {0, 0, 4, 4}; Output : 16 Input : X[] = {0,
6 min read
Tangents between two Convex PolygonsGiven two convex polygons, we aim to identify the lower and upper tangents connecting them. As shown in the figure below, TRL and TLR represent the upper and lower tangents, respectively. Examples: Input: First Polygon : [[2, 2], [3, 3], [5, 2], [4, 0], [3, 1]] Second Polygon : [[-1, 0], [0, 1], [1,
15 min read
Find number of diagonals in n sided convex polygonGiven n > 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 : 5Outp
3 min read
Convex Hull using Jarvis' Algorithm or WrappingGiven 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 leftmo
13 min read
Convex Hull using Graham ScanA 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 polygon in which all interior angles ar
15+ min read
Dynamic Convex hull | Adding Points to an Existing Convex HullGiven 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)
15 min read
Deleting points from Convex HullGiven 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,
15+ min read
Minimum area of a Polygon with three points givenGiven three points of a regular polygon(n > 3), find the minimum area of a regular polygon (all sides same) possible with the points given.Examples: Input : 0.00 0.00 1.00 1.00 0.00 1.00 Output : 1.00 By taking point (1.00, 0.00) square is formed of side 1.0 so area = 1.00 . One thing to note in
13 min read
Find Simple Closed Path for a given set of points Given a set of points, connect the dots without crossing. Example: Input: points[] = {(0, 3), (1, 1), (2, 2), (4, 4), (0, 0), (1, 2), (3, 1}, {3, 3}}; Output: Connecting points in following order would not cause any crossing {(0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3)} We strongl
11 min read
Minimum Distance between Two Points You are given an array arr[] of n distinct points in a 2D plane, where each point is represented by its (x, y) coordinates. Find the minimum Euclidean distance between two distinct points.Note: For two points A(px,qx) and B(py,qy) the distance Euclidean between them is:Distance = \sqrt{(p_{x}-q_{x})
15+ min read