The Wayback Machine - https://web.archive.org/web/20240917225923/https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
Open In App

How to check if two given line segments intersect?

Last Updated : 13 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
24.51%
47.6K

Given two line segments (p1, q1) and (p2, q2), find if the given line segments intersect with each other.
Before we discuss the solution, let us define notion of orientation. Orientation of an ordered triplet of points in the plane can be 
–counterclockwise 
–clockwise 
–collinear 

The following diagram shows different possible orientations of (a, b, c) 

How is Orientation useful here? 
Two segments (p1,q1) and (p2,q2) intersect if and only if one of the following two conditions is verified

1. General Case: 
– (p1, q1, p2) and (p1, q1, q2) have different orientations and 
– (p2, q2, p1) and (p2, q2, q1) have different orientations.

Examples:  

2. Special Case 
– (p1, q1, p2), (p1, q1, q2), (p2, q2, p1), and (p2, q2, q1) are all collinear and 
– the x-projections of (p1, q1) and (p2, q2) intersect 
– the y-projections of (p1, q1) and (p2, q2) intersect

Examples:  

Following is the implementation based on the above idea.  

C++




// A C++ program to check if two given line segments intersect
#include <iostream>
using namespace std;
  
struct Point
{
    int x;
    int y;
};
  
// Given three collinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
    if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
        q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
       return true;
  
    return false;
}
  
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are collinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
    // for details of below formula.
    int val = (q.y - p.y) * (r.x - q.x) -
              (q.x - p.x) * (r.y - q.y);
  
    if (val == 0) return 0;  // collinear
  
    return (val > 0)? 1: 2; // clock or counterclock wise
}
  
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
    // Find the four orientations needed for general and
    // special cases
    int o1 = orientation(p1, q1, p2);
    int o2 = orientation(p1, q1, q2);
    int o3 = orientation(p2, q2, p1);
    int o4 = orientation(p2, q2, q1);
  
    // General case
    if (o1 != o2 && o3 != o4)
        return true;
  
    // Special Cases
    // p1, q1 and p2 are collinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;
  
    // p1, q1 and q2 are collinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;
  
    // p2, q2 and p1 are collinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;
  
     // p2, q2 and q1 are collinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;
  
    return false; // Doesn't fall in any of the above cases
}
  
// Driver program to test above functions
int main()
{
    struct Point p1 = {1, 1}, q1 = {10, 1};
    struct Point p2 = {1, 2}, q2 = {10, 2};
  
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";
  
    p1 = {10, 0}, q1 = {0, 10};
    p2 = {0, 0}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";
  
    p1 = {-5, -5}, q1 = {0, 0};
    p2 = {1, 1}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";
  
    return 0;
}


Java




// Java program to check if two given line segments intersect
class GFG 
{
  
static class Point
{
    int x;
    int y;
  
        public Point(int x, int y) 
        {
            this.x = x;
            this.y = y;
        }
      
};
  
// Given three collinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
static boolean onSegment(Point p, Point q, Point r)
{
    if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) &&
        q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y))
    return true;
  
    return false;
}
  
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are collinear
// 1 --> Clockwise
// 2 --> Counterclockwise
static int orientation(Point p, Point q, Point r)
{
    // for details of below formula.
    int val = (q.y - p.y) * (r.x - q.x) -
            (q.x - p.x) * (r.y - q.y);
  
    if (val == 0) return 0; // collinear
  
    return (val > 0)? 1: 2; // clock or counterclock wise
}
  
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
static boolean doIntersect(Point p1, Point q1, Point p2, Point q2)
{
    // Find the four orientations needed for general and
    // special cases
    int o1 = orientation(p1, q1, p2);
    int o2 = orientation(p1, q1, q2);
    int o3 = orientation(p2, q2, p1);
    int o4 = orientation(p2, q2, q1);
  
    // General case
    if (o1 != o2 && o3 != o4)
        return true;
  
    // Special Cases
    // p1, q1 and p2 are collinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;
  
    // p1, q1 and q2 are collinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;
  
    // p2, q2 and p1 are collinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;
  
    // p2, q2 and q1 are collinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;
  
    return false; // Doesn't fall in any of the above cases
}
  
// Driver code
public static void main(String[] args) 
{
    Point p1 = new Point(1, 1);
    Point q1 = new Point(10, 1);
    Point p2 = new Point(1, 2);
    Point q2 = new Point(10, 2);
  
    if(doIntersect(p1, q1, p2, q2))
        System.out.println("Yes");
    else
        System.out.println("No");
  
    p1 = new Point(10, 1); q1 = new Point(0, 10);
    p2 = new Point(0, 0); q2 = new Point(10, 10);
    if(doIntersect(p1, q1, p2, q2))
            System.out.println("Yes");
    else
        System.out.println("No");
  
    p1 = new Point(-5, -5); q1 = new Point(0, 0);
    p2 = new Point(1, 1); q2 = new Point(10, 10);;
    if(doIntersect(p1, q1, p2, q2))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
  
// This code is contributed by Princi Singh


Python3




# A Python3 program to find if 2 given line segments intersect or not
  
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
  
# Given three collinear points p, q, r, the function checks if 
# point q lies on line segment 'pr' 
def onSegment(p, q, r):
    if ( (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and 
           (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))):
        return True
    return False
  
def orientation(p, q, r):
    # to find the orientation of an ordered triplet (p,q,r)
    # function returns the following values:
    # 0 : Collinear points
    # 1 : Clockwise points
    # 2 : Counterclockwise
      
    # for details of below formula. 
      
    val = (float(q.y - p.y) * (r.x - q.x)) - (float(q.x - p.x) * (r.y - q.y))
    if (val > 0):
          
        # Clockwise orientation
        return 1
    elif (val < 0):
          
        # Counterclockwise orientation
        return 2
    else:
          
        # Collinear orientation
        return 0
  
# The main function that returns true if 
# the line segment 'p1q1' and 'p2q2' intersect.
def doIntersect(p1,q1,p2,q2):
      
    # Find the 4 orientations required for 
    # the general and special cases
    o1 = orientation(p1, q1, p2)
    o2 = orientation(p1, q1, q2)
    o3 = orientation(p2, q2, p1)
    o4 = orientation(p2, q2, q1)
  
    # General case
    if ((o1 != o2) and (o3 != o4)):
        return True
  
    # Special Cases
  
    # p1 , q1 and p2 are collinear and p2 lies on segment p1q1
    if ((o1 == 0) and onSegment(p1, p2, q1)):
        return True
  
    # p1 , q1 and q2 are collinear and q2 lies on segment p1q1
    if ((o2 == 0) and onSegment(p1, q2, q1)):
        return True
  
    # p2 , q2 and p1 are collinear and p1 lies on segment p2q2
    if ((o3 == 0) and onSegment(p2, p1, q2)):
        return True
  
    # p2 , q2 and q1 are collinear and q1 lies on segment p2q2
    if ((o4 == 0) and onSegment(p2, q1, q2)):
        return True
  
    # If none of the cases
    return False
  
# Driver program to test above functions:
p1 = Point(1, 1)
q1 = Point(10, 1)
p2 = Point(1, 2)
q2 = Point(10, 2)
  
if doIntersect(p1, q1, p2, q2):
    print("Yes")
else:
    print("No")
  
p1 = Point(10, 0)
q1 = Point(0, 10)
p2 = Point(0, 0)
q2 = Point(10,10)
  
if doIntersect(p1, q1, p2, q2):
    print("Yes")
else:
    print("No")
  
p1 = Point(-5,-5)
q1 = Point(0, 0)
p2 = Point(1, 1)
q2 = Point(10, 10)
  
if doIntersect(p1, q1, p2, q2):
    print("Yes")
else:
    print("No")
      
# This code is contributed by Ansh Riyal


C#




// C# program to check if two given line segments intersect
using System;
using System.Collections.Generic; 
  
class GFG 
{
  
public class Point
{
    public int x;
    public int y;
  
    public Point(int x, int y) 
    {
        this.x = x;
        this.y = y;
    }
      
};
  
// Given three collinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
static Boolean onSegment(Point p, Point q, Point r)
{
    if (q.x <= Math.Max(p.x, r.x) && q.x >= Math.Min(p.x, r.x) &&
        q.y <= Math.Max(p.y, r.y) && q.y >= Math.Min(p.y, r.y))
    return true;
  
    return false;
}
  
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are collinear
// 1 --> Clockwise
// 2 --> Counterclockwise
static int orientation(Point p, Point q, Point r)
{
    // for details of below formula.
    int val = (q.y - p.y) * (r.x - q.x) -
            (q.x - p.x) * (r.y - q.y);
  
    if (val == 0) return 0; // collinear
  
    return (val > 0)? 1: 2; // clock or counterclock wise
}
  
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
static Boolean doIntersect(Point p1, Point q1, Point p2, Point q2)
{
    // Find the four orientations needed for general and
    // special cases
    int o1 = orientation(p1, q1, p2);
    int o2 = orientation(p1, q1, q2);
    int o3 = orientation(p2, q2, p1);
    int o4 = orientation(p2, q2, q1);
  
    // General case
    if (o1 != o2 && o3 != o4)
        return true;
  
    // Special Cases
    // p1, q1 and p2 are collinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;
  
    // p1, q1 and q2 are collinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;
  
    // p2, q2 and p1 are collinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;
  
    // p2, q2 and q1 are collinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;
  
    return false; // Doesn't fall in any of the above cases
}
  
// Driver code
public static void Main(String[] args) 
{
    Point p1 = new Point(1, 1);
    Point q1 = new Point(10, 1);
    Point p2 = new Point(1, 2);
    Point q2 = new Point(10, 2);
  
    if(doIntersect(p1, q1, p2, q2))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
  
    p1 = new Point(10, 1); q1 = new Point(0, 10);
    p2 = new Point(0, 0); q2 = new Point(10, 10);
    if(doIntersect(p1, q1, p2, q2))
            Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
  
    p1 = new Point(-5, -5); q1 = new Point(0, 0);
    p2 = new Point(1, 1); q2 = new Point(10, 10);;
    if(doIntersect(p1, q1, p2, q2))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
  
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
// Javascript program to check if two given line segments intersect
  
class Point
{
    constructor(x, y)
    {
        this.x = x;
            this.y = y;
    }
}
  
// Given three collinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
function onSegment(p, q, r)
{
    if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) &&
        q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y))
    return true;
    
    return false;
}
  
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are collinear
// 1 --> Clockwise
// 2 --> Counterclockwise
function orientation(p, q, r)
{
  
    // for details of below formula.
    let val = (q.y - p.y) * (r.x - q.x) -
            (q.x - p.x) * (r.y - q.y);
    
    if (val == 0) return 0; // collinear
    
    return (val > 0)? 1: 2; // clock or counterclock wise
}
  
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
function doIntersect(p1, q1, p2, q2)
{
  
    // Find the four orientations needed for general and
    // special cases
    let o1 = orientation(p1, q1, p2);
    let o2 = orientation(p1, q1, q2);
    let o3 = orientation(p2, q2, p1);
    let o4 = orientation(p2, q2, q1);
    
    // General case
    if (o1 != o2 && o3 != o4)
        return true;
    
    // Special Cases
    // p1, q1 and p2 are collinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;
    
    // p1, q1 and q2 are collinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;
    
    // p2, q2 and p1 are collinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;
    
    // p2, q2 and q1 are collinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;
    
    return false; // Doesn't fall in any of the above cases
}
  
// Driver code
let p1 = new Point(1, 1);
let q1 = new Point(10, 1);
let p2 = new Point(1, 2);
let q2 = new Point(10, 2);
  
if(doIntersect(p1, q1, p2, q2))
    document.write("Yes<br>");
else
    document.write("No<br>");
  
p1 = new Point(10, 1); q1 = new Point(0, 10);
p2 = new Point(0, 0); q2 = new Point(10, 10);
if(doIntersect(p1, q1, p2, q2))
    document.write("Yes<br>");
else
    document.write("No<br>");
  
p1 = new Point(-5, -5); q1 = new Point(0, 0);
p2 = new Point(1, 1); q2 = new Point(10, 10);;
if(doIntersect(p1, q1, p2, q2))
    document.write("Yes<br>");
else
    document.write("No<br>");
  
// This code is contributed by avanitrachhadiya2155
</script>


Output: 

No
Yes
No

Time Complexity: O(1)

Space Complexity: O(1)

Sources: 
http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf 
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest

 



Previous Article
Next Article

Similar Reads

Given n line segments, find if any two segments intersect
Given n line segments (p1, q1), (p2, q2), ... (pn, qn), find if the given line segments intersect with each other or not. Example: Input: {{1, 5}, {4, 5}}, {{2, 5}, {10, 1}},{{3, 2}, {10, 3}},{{6, 4}, {9, 4}},{{7, 1}, {8, 1}}Output: 2Explanation: Lines {{1, 5}, {4, 5}}, {{2, 5}, {10, 1}} are intersecting, as well as {{2, 5}, {10, 1}},{{3, 2}, {10,
10 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Minimize segments required to be removed such that at least one segment intersects with all remaining segments
Given an array arr[] consisting of N pairs [L, R], where L and R denotes the start and end indices of a segment, the task is to find the minimum number of segments that must be deleted from the array such that the remaining array contains at least one segment which intersects with all other segments present in the array. Examples: Input: arr[] = {{
10 min read
Maximum sum of segments among all segments formed in array after Q queries
Given two arrays arr[](1-based indexing) and queries[] consisting of N integers and queries[] contains a permutation of the first N natural numbers, the task is to perform the query on the array and find the maximum sum of segments among all segments formed such that in each query queries[i] the array element at index queries[i] is deleted and that
15 min read
Check if two given circles touch or intersect each other
There 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) R1 = 12, R2 = 10Output : Circles intersect with eac
5 min read
Find line which does not intersect with parabola
Given N straight lines of form y = k * x. Also, given M parabolas of form y = a * x2 + b * x + c where a &gt; 0. For each parabola, choose a line that does not intersect this parabola and does not touch it, the task is to find such a line for each parabola or to determine if there is no such line. Print "Yes" and the value of K for the line if the
8 min read
Check if two circles intersect such that the third circle passes through their points of intersections and centers
Given centres and the radii of three circles A, B, and C in the form of {X, Y, R}, where (X, Y) is the centre of the circle and R is the radius of that circle. The task is to check if any two circles intersect such that the third circle passes through the intersecting points and the centres of the two circles. If found to be true, then print "Yes".
9 min read
Check if there exists two non-intersect ranges
Given two non-negative integers X and Y, the task is to output the two non-intersecting ranges of non-negative integers such that the sum of the starting and ending point of the first range is equal to X and the product of the starting and ending point of the second range is equal Y. If there is no possible answer output -1. If there are multiple p
7 min read
Given a linked list of line segments, remove middle points
Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line. Examples: Input: (0,10)-&gt;(1,10)-&gt;(5,10)-&gt;(7,10) | (7,5)-&gt;(20,5)-&gt;(40,5) Output: Linked List should be changed to following (0,10)-&gt;(
14 min read
Maximum number of parallelograms that can be made using the given length of line segments
Given N line segments where the length of the ith line segment is [Tex]a_i [/Tex]. The task is to find the maximum number of parallelograms can be made with those line segments if each line segment is used at most in one parallelogram.Examples: Input: arr[] = {1, 2, 1, 2} Output: 1 Only one parallelogram can be made with sides 1, 2, 1, 2 Input: arr
6 min read
Count number of triangles cut by the given horizontal and vertical line segments
Given an array triangles[][] consisting of N triangles of the form {x1, y1, x2, y2, x3, y3} and an array cuts[] consisting of M horizontal and vertical lines of the form "X=x" or "Y=y" which represents the equation of the line segments. The task is to print the number of triangles intersected by each cut in such a way that the left and the right pa
13 min read
Minimum points to be selected such that removal of line segments passing through them empties given array
Given a 2D array arr[][], where each row is of the form {start, end} representing the start and endpoints of each line segment on the X-axis. In one step, select a point on the X-axis and delete all the line segments passing through that point. The task is to find the minimum number of such points that need to be selected to delete all the line seg
7 min read
Number of horizontal or vertical line segments to connect 3 points
Given three points on the x-y coordinate plane. You need to find the no. of line segments formed by making a polyline passing through these points. (Line segment can be vertically or horizontally aligned to the coordinate axis) Examples : Input : A = {-1, -1}, B = {-1, 3}, C = {4, 3} Output : 2 Expantaion: There are two segments in this polyline. I
8 min read
Iterative approach for removing middle points in a linked list of line segments
This post explains the iterative approach of this problem. We maintain two pointers, prev and temp. If these two have either x or y same, we move forward till the equality holds and keep deleting the nodes in between. The node from which the equality started, we adjust the next pointer of that node. Implementation: C/C++ Code // C++ program to remo
9 min read
Maximum possible intersection by moving centers of line segments
Given three points on the X-axis which denotes the center of three line segments. The length of the line segment is also given as L. The task is to move the center of the given line segments by a distance of K to maximize the length of intersection between the three lines. Examples: Input: c1 = 1, c2 = 2, c3 = 3, L = 1, K = 0 Output: 0 Since, no ce
5 min read
Number of ways to choose K intersecting line segments on X-axis
Given an array arr[] of line segments on the x-axis and an integer K, the task is to calculate the number of ways to choose the K line-segments such that they do intersect at any point. Since the answer can be large, print it to modulo 10^9+7. Examples: Input: arr[] = [[1, 3], [4, 5], [5, 7]], K = 2 Output: 2 Explanation: The first way to choose [1
10 min read
Maximize count of intersecting line segments
Given two arrays X[] and Y[], representing points on X and Y number lines, such that every similar-indexed array element forms a line segment, i.e. X[i] and Y[i] forms a line segment, the task is to find the maximum number of line segments that can be selected from the given array. Examples: Input: X[] = {0, 3, 4, 1, 2}, Y[] = {3, 2, 0, 1, 4}Output
9 min read
Javascript Program For Removing Middle Points From a Linked List Of Line Segments
Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line.Examples: Input: (0,10)-&gt;(1,10)-&gt;(5,10)-&gt;(7,10) | (7,5)-&gt;(20,5)-&gt;(40,5) Output: Linked List should be changed to following (0,10)-&gt;(7
4 min read
Finding the number of triangles amongst horizontal and vertical line segments
Prerequisites: BIT Given 'n' line segments, each of them is either horizontal or vertical, find the maximum number of triangles(including triangles with zero area) that can be formed by joining the intersection points of the line segments. No two horizontal line segments overlap, nor do two vertical line segments. A line is represented using two po
6 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 take the union of all the line segments, we cover di
9 min read
Find if there exists a direction for ranges such that no two range intersect
Given N ranges [L, R] with velocities vel[]. The task is to assign each range a direction i.e. either left or right. All the ranges will start moving in the assigned direction at time t = 0. Find, if there is an assignment of directions possible given that no two ranges overlap at infinite time.Examples: Input: range[][] = {{1, 2}, {2, 5}, {3, 10},
8 min read
Minimize group such that no two range of same group intersect
Given an array ranges[] of size N (1 ? N ? 105), where ranges[i] = {starti, endi} represents the range between starti to endi (both inclusive). The task is to find the minimum number of groups that are needed such that each interval of ranges[] belongs to exactly one group and no two ranges[i] in the same group will intersect with each other. Note:
8 min read
Check if any pair of semicircles intersect or not
Given an array arr[] consisting of N integers such that each pair of points (x, y) represents the endpoints of the semicircle as (x, 0) and (y, 0), the task is to check if any pair of semicircles intersect or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {0, 15, 5, 10}Output: No Input: arr[] = {0, 10, 5
8 min read
Check if a large number can be divided into two or more segments of equal sum
Given a very large Number N. The task is to check if the number can be divided into two or more segments of an equal sum. Examples: Input: N = 73452 Output: Yes Segments of {7}, {3, 4}, {5, 2} which has equal sum of 7 Input: N = 1248 Output: No The following steps can be followed to solve the problem: Since the number can be large, the number is in
8 min read
Divide N segments into two non-empty groups such that given condition is satisfied
Given N segments (or ranges) represented by two non-negative integers L and R. Divide these segments into two non-empty groups such that there are no two segments from different groups that share a common point. If it is possible to do so, assign each segment a number from the set {1, 2} otherwise print Not Possible. Examples: Input: arr[][] = {{5,
9 min read
Equation of a straight line passing through a point and making a given angle with a given line
Given four integers a, b, c representing coefficients of a straight line with equation (ax + by + c = 0), the task is to find the equations of the two straight lines passing through a given point [Tex](x1, y1) [/Tex]and making an angle ? with the given straight line. Examples: Input: a = 2, b = 3, c = -7, x1 = 4, y1 = 9, ? = 30Output: y = -0.49x +1
15+ min read
Level order traversal line by line | Set 2 (Using Two Queues)
Given a Binary Tree, print the nodes level wise, each level on a new line. Output: 1 2 3 4 5Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. We have discussed one solution in below article. Print level order traversal line by line | Set 1 In this post, a different approach using two queues is discussed. We can ins
7 min read
Maximum number of intervals that an interval can intersect
Given an array arr[] consisting of N intervals of the form of [L, R], where L, R denotes the start and end positions of the interval, the task is to count the maximum number of intervals that an interval can intersect with each other. Examples: Input: arr[] = {{1, 2}, {3, 4}, {2, 5}}Output: 3Explanation: The required set of intervals are {1, 2}, {2
15+ min read
Number of parallelograms when n horizontal parallel lines intersect m vertical parallel lines
Given 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 = 5, m = 5Output : 100 The idea is to use Combinati
8 min read
Determine if possible to get Array by breaking rod segments into two halves
Given a rod of length L and an array arr[] of length N, the task is to find if it is possible to break the rod N-1 times in segments such that length of all the segments is present in the array. Each time a segment of length x can be broken into two parts of length ⌈x/2⌉ and x - ⌈x/2⌉. Examples: Input: L = 1000, N = 1, arr[] = {1000} Output: YESExp
7 min read