Angular Sweep (Maximum points that can be enclosed in a circle of given radius)
Last Updated :
28 Mar, 2024
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),
(6.69533 6.20378)}
Output: 2
The maximum number of points is 2
Input: R = 1
points[] = {(6.65128, 5.47490), (6.42743, 6.26189)
(6.35864, 4.61611), (6.59020 4.54228), (4.43967 5.70059)
(4.38226, 5.70536), (5.50755 6.18163), (7.41971 6.13668)
(6.71936, 3.04496), (5.61832, 4.23857), (5.99424, 4.29328)
(5.60961, 4.32998), (6.82242, 5.79683), (5.44693, 3.82724) |
(6.70906, 3.65736), (7.89087, 5.68000), (6.23300, 4.59530)
(5.92401, 4.92329), (6.24168, 3.81389), (6.22671, 3.62210)}
Output: 11
The maximum number of points is 11
Naive Algorithm:
For an arbitrary pair of points in the given set (say A and B), construct the circles with radius ‘R’ that touches both the points. There are maximum 2 such possible circles. As we can see here maximum possible circles is for CASE 1 i.e. 2.

- For each of the constructed circle, check for each point in the set if it lies inside the circle or not.
- The circle with maximum number of points enclosed is returned.
Time Complexity: There are nC2 pair of points corresponding to which we can have 2nC2 circles at maximum. For each circle, (n-2) points have to be checked. This makes the naive algorithm O(n3).
Angular Sweep Algorithm:
By using Angular Sweep, we can solve this problem in O(n2log n). The basic logical idea of this algorithm is described below.
We pick an arbitrary point P from the given set. We then rotate a circle with fixed-radius ‘R’ about the point P. During the entire rotation P lies on the circumference of the circle and we maintain a count of the number of points in the circle at a given value of ? where the parameter ? determines the angle of rotation. The state of a circle can thus be determined by a single parameter ? because the radius is fixed.
We can also see that the value of the count maintained will change only when a point from the set enters or exits the circle.
In the given diagram, C1 is the circle with ? = 0 and C2 is the circle constructed when we rotate the circle at a general value of ?.
After this, the problem reduces to, how to maintain the value of count.
For any given point except P (say Q), we can easily calculate the value of ? for which it enters the circle (Let it be ?) and the value of ? for which it exits the circle (Let it be ?).
We have angles A and B defined as under,
- A is the angle between PQ and the X-Axis.
- B is the angle between PC and PQ where C is the centre of the circle.
A = tan^{-1} \frac{(P.y – Q.y)}{(P.x-Q.x)} \\\\ B = cos^{-1} \frac{d}{2R}
where, x and y represent the coordinates of a point and ‘d’ is the distance between P and Q.
Now, from the diagrams we can see that,
? = A-B
? = A+B
(Note: All angles are w.r.t. to X-Axis. Thus, it becomes ‘A-B’ and not ‘B-A’).
When Q enters the circle

When Q exits the circle

We can calculate angles A and B for all points excluding P. Once these angles are found, we sort them and then traverse them in increasing order. Now we maintain a counter which tells us how many points are inside the circle at a particular moment.
Count will change only when a point enters the circle or exits it. In case we find an entry angle we increase the counter by 1 and in case we find an exit angle we decrease the counter by 1. The check that the angle is entry or exit can be easily realised using a flag.
Proceeding like this, the counter always gives us a valid value for the number of points inside the circle in a particular state.
Important Note: The points which have ‘d’>2R do not have to be considered because they will never enter or exit the circle.
The angular sweep algorithm can be described as:
- Calculate the distance between every pair of nC2 points and store them.
- For an arbitrary point (say P), get the maximum number of points that can lie inside the circle rotated about P using the getPointsInside() function.
- The maximum of all values returned will be the final answer.
Below is the implementation of the above approach:
CPP
// C++ program to find the maximum number of
// points that can be enclosed by a fixed-radius
// circle
#include <bits/stdc++.h>
using namespace std;
const int MAX_POINTS = 500;
// complex class which is available in STL has
// been used to implement points. This helps to
// ensure greater functionality easily
typedef complex<double> Point;
Point arr[MAX_POINTS];
double dis[MAX_POINTS][MAX_POINTS];
// This function returns the maximum points that
// can lie inside the circle of radius 'r' being
// rotated about point 'i'
bool mycompare(pair<double,bool> A, pair<double,bool> B)
{
if(A.first<B.first)
return true;
else if(A.first>B.first)
return false;
else
return (A.second==1);
}
int getPointsInside(int i, double r, int n)
{
// This vector stores alpha and beta and flag
// is marked true for alpha and false for beta
vector<pair<double, bool> > angles;
for (int j=0; j<n; j++)
{
if (i != j && dis[i][j] <= 2*r)
{
// acos returns the arc cosine of the complex
// used for cosine inverse
double B = acos(dis[i][j]/(2*r));
// arg returns the phase angle of the complex
double A = arg(arr[j]-arr[i]);
double alpha = A-B;
double beta = A+B;
angles.push_back(make_pair(alpha, true));
angles.push_back(make_pair(beta, false));
}
}
// angles vector is sorted and traversed
sort(angles.begin(), angles.end(), mycompare);
// count maintains the number of points inside
// the circle at certain value of theta
// res maintains the maximum of all count
int count = 1, res = 1;
vector<pair<double, bool> >::iterator it;
for (it=angles.begin(); it!=angles.end(); ++it)
{
// entry angle
if ((*it).second)
count++;
// exit angle
else
count--;
if (count > res)
res = count;
}
return res;
}
// Returns count of maximum points that can lie
// in a circle of radius r.
int maxPoints(Point arr[], int n, int r)
{
// dis array stores the distance between every
// pair of points
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)
// abs gives the magnitude of the complex
// number and hence the distance between
// i and j
dis[i][j] = dis[j][i] = abs(arr[i]-arr[j]);
// This loop picks a point p
int ans = 0;
for (int i=0; i<n; i++)
// maximum number of points for point arr[i]
ans = max(ans, getPointsInside(i, r, n));
return ans;
}
// Driver code
int main()
{
Point arr[] = {Point(6.47634, 7.69628),
Point(5.16828, 4.79915),
Point(6.69533, 6.20378)};
int r = 1;
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The maximum number of points are: "
<< maxPoints(arr, n, r);
return 0;
}
Java
import java.util.*;
class MaximumPointsInCircle {
static final int MAX_POINTS = 500;
static Point[] arr = new Point[MAX_POINTS];
static double[][] dis = new double[MAX_POINTS][MAX_POINTS];
static class Point {
double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
static int mycompare(AbstractMap.SimpleEntry<Double, Boolean> A, AbstractMap.SimpleEntry<Double, Boolean> B) {
if (A.getKey() < B.getKey())
return -1;
else if (A.getKey() > B.getKey())
return 1;
else
return (A.getValue() ? 1 : -1);
}
static int getPointsInside(int i, double r, int n) {
List<AbstractMap.SimpleEntry<Double, Boolean>> angles = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (i != j && dis[i][j] <= 2 * r) {
double B = Math.acos(dis[i][j] / (2 * r));
double A = Math.atan2(arr[j].y - arr[i].y, arr[j].x - arr[i].x);
double alpha = A - B;
double beta = A + B;
angles.add(new AbstractMap.SimpleEntry<>(alpha, true));
angles.add(new AbstractMap.SimpleEntry<>(beta, false));
}
}
angles.sort((A, B) -> mycompare(A, B));
int count = 1, res = 1;
for (AbstractMap.SimpleEntry<Double, Boolean> angle : angles) {
if (angle.getValue())
count++;
else
count--;
if (count > res)
res = count;
}
return res;
}
static int maxPoints(Point[] arr, int n, int r) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
dis[i][j] = dis[j][i] = Math.hypot(arr[i].x - arr[j].x, arr[i].y - arr[j].y);
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, getPointsInside(i, r, n));
}
return ans;
}
public static void main(String[] args) {
arr[0] = new Point(6.47634, 7.69628);
arr[1] = new Point(5.16828, 4.79915);
arr[2] = new Point(6.69533, 6.20378);
int r = 1;
int n = 3;
System.out.println("The maximum number of points are: " + maxPoints(arr, n, r));
}
}
C#
using System;
using System.Collections.Generic;
public struct Complex
{
public double Real;
public double Imaginary;
public Complex(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static Complex operator -(Complex a, Complex b)
{
return new Complex(a.Real - b.Real, a.Imaginary - b.Imaginary);
}
public static double Abs(Complex c)
{
return Math.Sqrt(c.Real * c.Real + c.Imaginary * c.Imaginary);
}
public static double Atan2(double y, double x)
{
return Math.Atan2(y, x);
}
}
public class Program
{
const int MAX_POINTS = 500;
// This function returns the maximum points that
// can lie inside the circle of radius 'r' being
// rotated about point 'i'
static int GetPointsInside(int i, double r, int n, Complex[] arr, double[,] dis)
{
// This list stores alpha and beta and flag
// is marked true for alpha and false for beta
List<(double, bool)> angles = new List<(double, bool)>();
for (int j = 0; j < n; j++)
{
if (i != j && dis[i, j] <= 2 * r)
{
// acos returns the arc cosine of the complex
// used for cosine inverse
double B = Math.Acos(dis[i, j] / (2 * r));
// arg returns the phase angle of the complex
double A = Complex.Atan2(arr[j].Imaginary - arr[i].Imaginary, arr[j].Real - arr[i].Real);
double alpha = A - B;
double beta = A + B;
angles.Add((alpha, true));
angles.Add((beta, false));
}
}
// angles list is sorted and traversed
angles.Sort(CompareAngles);
// count maintains the number of points inside
// the circle at certain value of theta
// res maintains the maximum of all count
int count = 1, res = 1;
foreach (var angle in angles)
{
// entry angle
if (angle.Item2)
count++;
// exit angle
else
count--;
if (count > res)
res = count;
}
return res;
}
// Returns count of maximum points that can lie
// in a circle of radius r.
static int MaxPoints(Complex[] arr, int n, int r)
{
// dis array stores the distance between every
// pair of points
double[,] dis = new double[n, n];
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
// abs gives the magnitude of the complex
// number and hence the distance between
// i and j
dis[i, j] = dis[j, i] = Complex.Abs(arr[i] - arr[j]);
// This loop picks a point p
int ans = 0;
for (int i = 0; i < n; i++)
// maximum number of points for point arr[i]
ans = Math.Max(ans, GetPointsInside(i, r, n, arr, dis));
return ans;
}
// Custom comparer for sorting angles
static int CompareAngles((double, bool) A, (double, bool) B)
{
if (A.Item1 < B.Item1)
return -1;
else if (A.Item1 > B.Item1)
return 1;
else
return A.Item2.CompareTo(B.Item2);
}
// Driver code
public static void Main(string[] args)
{
Complex[] arr = {
new Complex(6.47634, 7.69628),
new Complex(5.16828, 4.79915),
new Complex(6.69533, 6.20378)
};
int r = 1;
int n = arr.Length;
Console.WriteLine("The maximum number of points are: " + MaxPoints(arr, n, r));
}
}
JavaScript
// JavaScript program to find the maximum number of
// points that can be enclosed by a fixed-radius
// circle
const MAX_POINTS = 500;
// complex class which has
// been used to implement points. This helps to
// ensure greater functionality easily
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
subtract(other) {
return new Point(this.x - other.x, this.y - other.y);
}
magnitude() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
arg() {
return Math.atan2(this.y, this.x);
}
}
const arrPoints = [new Point(6.47634, 7.69628),
new Point(5.16828, 4.79915),
new Point(6.69533, 6.20378)];
const dis = new Array(MAX_POINTS).fill(0).map(() => new Array(MAX_POINTS).fill(0));
// This function returns the maximum points that
// can lie inside the circle of radius 'r' being
// rotated about point 'i'
function mycompare(A, B) {
if (A.first < B.first) {
return -1;
} else if (A.first > B.first) {
return 1;
} else {
return A.second == 1 ? -1 : 1;
}
}
function getPointsInside(i, r, n) {
// This vector stores alpha and beta and flag
// is marked true for alpha and false for beta
let angles = [];
for (let j = 0; j < n; j++) {
if (i != j && dis[i][j] <= 2 * r) {
// acos returns the arc cosine of the complex
// used for cosine inverse
let B = Math.acos(dis[i][j] / (2 * r));
// arg returns the phase angle of the complex
let A = arrPoints[j].subtract(arrPoints[i]).arg();
let alpha = A - B;
let beta = A + B;
angles.push([alpha, true]);
angles.push([beta, false]);
}
}
// angles vector is sorted and traversed
angles.sort(mycompare);
// count maintains the number of points inside
// the circle at certain value of theta
// res maintains the maximum of all count
let count = 1;
let res = 1;
for (let i = 0; i < angles.length; i++) {
// entry angle
if (angles[i][1]) {
count++;
}
// exit angle
else {
count--;
}
if (count > res) {
res = count;
}
}
return res;
}
// Returns count of maximum points that can lie
// in a circle of radius r.
function maxPoints(arrPoints, n, r) {
// dis array stores the distance between every
// pair of points
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
// abs gives the magnitude of the complex
// number and hence the distance between
// i and j
dis[i][j] = dis[j][i] = arrPoints[i].subtract(arrPoints[j]).magnitude();
}
}
// This loop picks a point p
let ans = 0;
for (let i = 0; i < n; i++) {
// maximum number of points for point arr[i]
ans = Math.max(ans, getPointsInside(i, r, n));
}
return ans;
}
// Driver code
const n = arrPoints.length;
const r = 1;
console.log(`The maximum number of points are: ${maxPoints(arrPoints, n, r)}`);
// This Code is Contributed by Prasad Kandekar(prasad264)
Python3
# python program to find the maximum number of
# points that can be enclosed by a fixed-radius
# circle
import math
MAX_POINTS = 500
arr = [0] * MAX_POINTS
dis = [[0 for i in range(MAX_POINTS)] for j in range(MAX_POINTS)]
# This function returns the maximum points that
# can lie inside the circle of radius 'r' being
# rotated about point 'i'
def mycompare(A, B):
if A[0] < B[0]:
return True
elif A[0] > B[0]:
return False
else:
return A[1] == 1
def getPointsInside(i, r, n):
# This vector stores alpha and beta and flag
# is marked true for alpha and false for beta
angles = []
for j in range(n):
if i != j and dis[i][j] <= 2*r:
# acos returns the arc cosine of the complex
# used for cosine inverse
B = math.acos(dis[i][j]/(2*r))
# arg returns the phase angle of the complex
A = math.atan2(arr[j].imag - arr[i].imag, arr[j].real - arr[i].real)
alpha = A - B
beta = A + B
angles.append([alpha, True])
angles.append([beta, False])
# angles vector is sorted and traversed
angles.sort(key=lambda x: (x[0], x[1] == 1))
# count maintains the number of points inside
# the circle at certain value of theta
# res maintains the maximum of all count
count = 1
res = 1
for angle in angles:
# entry angle
if angle[1]:
count += 1
# exit angle
else:
count -= 1
res = max(res, count)
return res
# Returns count of maximum points that can lie
# in a circle of radius r.
def maxPoints(arr, n, r):
# dis array stores the distance between every
# pair of points
for i in range(n - 1):
for j in range(i + 1, n):
# abs gives the magnitude of the complex
# number and hence the distance between
# i and j
dis[i][j] = dis[j][i] = abs(arr[i] - arr[j])
# This loop picks a point p
ans = 0
for i in range(n):
# maximum number of points for point arr[i]
ans = max(ans, getPointsInside(i, r, n))
return ans
# Driver code
r = 1
arr = [complex(6.47634, 7.69628),
complex(5.16828, 4.79915),
complex(6.69533, 6.20378)]
n = len(arr)
print("The maximum number of points are:", maxPoints(arr, n, r))
# This Code is Contributed by Prasad Kandekar(prasad264)
Output:
The maximum number of points are: 2
Time Complexity: There are n points for which we call the function getPointsInside(). This function works on ‘n-1’ points for which we get 2*(n-1) size of the vector ‘angles’ (one entry angle and one exit angle). Now this ‘angles’ vector is sorted and traversed which gives complexity of the getPointsInside() function equal to O(nlogn). This makes the Angular Sweep Algorithm O(n2log n).
Space complexity: O(n) since using auxiliary space for vector
Related Resources: Using the complex class available in stl for implementing solutions to geometry problems.
http://codeforces.com/blog/entry/22175
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