The Wayback Machine - https://web.archive.org/web/20240917065254/https://www.geeksforgeeks.org/number-of-ways-to-choose-k-intersecting-line-segments-on-x-axis/
Open In App

Number of ways to choose K intersecting line segments on X-axis

Last Updated : 16 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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, 3], [4, 5] and the second way is [1, 3], [5, 7].Since Intersection of [4, 5], [5, 7] is not zero and hence cannot be included in answer.

Input: [[3, 7], [1, 4], [6, 9], [8, 13], [9, 11]], K = 1 
Output: 0 
Explanation: 
Since we are only looking for single line segment, but for every single line segment Intersection is always non empty. 

Approach:
To solve the problem mentioned above we will try to find out the number of odd cases means those cases whose intersection is non-empty. So clearly our answer will be Total Case – Odd Case. 
To compute the total number of cases, the below approach is followed:  

  • Total cases that are possible are “n choose k” or nCk
  • We pre-calculate the inverse and factorial of required numbers to calculate nCk
  • in O(1) time
  • The K line-segment intersect as if min(R1, R2, .., R{k-1}) >= Li where line-segment [Li, Ri] is under consideration. Maintain a multiset, to maintain order. Firstly, sort the segments in increasing order of Li . If Li are same then the segment with smaller Ri comes first.

For every line-segment [Li, Ri], the approach below is followed to find the number of odd cases.  

  • While multiset is not empty, and the lines don’t intersect then delete the line with smallest Ri from multiset and check again.
  • Number of violating ways using this segment [Li, Ri] are pCk-1
  • where p = size_of_multiset.
  • Insert end-point of this line-segment in the multiset.

Below is the implementation of the above approach: 

C++




// C++ program to find Number of ways
// to choose K intersecting
// line segments on X-axis
 
#include <bits/stdc++.h>
using namespace std;
 
const long long mod = 1000000007;
const int MAXN = 1001;
long long factorial[MAXN], inverse[MAXN];
 
// Function to find (a^b)%mod in log b
long long power(long long a, long long b)
{
    long long res = 1;
 
    // Till power becomes 0
    while (b > 0) {
 
        // If power is odd
        if (b % 2 == 1) {
            res = (res * a) % mod;
        }
        // Multiply base
        a = (a * a) % mod;
 
        // Divide power by 1
        b >>= 1;
    }
 
    return res;
}
 
// Function to find nCk
long long nCk(int n, int k)
{
    // Base case
    if (k < 0 || k > n) {
        return 0;
    }
 
    // Apply formula to find nCk
    long long ans = factorial[n];
    ans = (ans * inverse[n - k]) % mod;
    ans = (ans * inverse[k]) % mod;
 
    return ans;
}
 
// Function to find the number of ways
void numberOfWays(vector<pair<int, int> > lines, int K,
                  int N)
{
 
    // sort the given lines
    sort(lines.begin(), lines.end());
 
    // Find the number of total case
    long long total_case = nCk(N, K);
 
    // Declare a multiset
    multiset<int> m;
 
    // loop till N
    for (int i = 0; i < N; i++)
    {
 
        // Check if smallest element is
        // smaller than lines[i]
        while (!m.empty()
               && (*m.begin() < lines[i].first)) {
 
            // Erase first element
            m.erase(m.begin());
        }
        // Exclude the odd cases
        total_case -= nCk(m.size(), K - 1);
 
        // Modulus operation
        total_case += mod;
        total_case %= mod;
 
        // Insert into multiset
        m.insert(lines[i].second);
    }
 
    cout << total_case << endl;
}
 
// Function to precompute
// factorial and inverse
void preCompute()
{
    long long fact = 1;
 
    factorial[0] = 1;
    inverse[0] = 1;
 
    // Pre-compute factorial and inverse
    for (int i = 1; i < MAXN; i++) {
 
        fact = (fact * i) % mod;
        factorial[i] = fact;
        inverse[i] = power(factorial[i], mod - 2);
    }
}
 
// Driver code
int main()
{
 
    int N = 3, K = 2;
    vector<pair<int, int> > lines;
 
    // Function to pre-compute
    // factorial and inverse
    preCompute();
 
    lines.push_back({ 1, 3 });
    lines.push_back({ 4, 5 });
    lines.push_back({ 5, 7 });
 
    numberOfWays(lines, K, N);
 
    return 0;
}


Java




// Java program to find Number of ways
// to choose K intersecting line
// segments on X-axis
import java.util.*;
import java.lang.*;
 
class GFG {
 
    static long mod = 1000000007;
    static int MAXN = 1001;
    static long factorial[] = new long[MAXN],
                inverse[] = new long[MAXN];
 
    // Function to find (a^b)%mod in log b
    static long power(long a, long b)
    {
        long res = 1;
 
        // Till power becomes 0
        while (b > 0) {
 
            // If power is odd
            if (b % 2 == 1) {
                res = (res * a) % mod;
            }
 
            // Multiply base
            a = (a * a) % mod;
 
            // Divide power by 1
            b >>= 1;
        }
        return res;
    }
 
    // Function to find nCk
    static long nCk(int n, int k)
    {
 
        // Base case
        if (k < 0 || k > n) {
            return 0;
        }
 
        // Apply formula to find nCk
        long ans = factorial[n];
        ans = (ans * inverse[n - k]) % mod;
        ans = (ans * inverse[k]) % mod;
 
        return ans;
    }
 
    // Function to find the number of ways
    static void numberOfWays(ArrayList<int[]> lines, int K,
                             int N)
    {
 
        // sort the given lines
        Collections.sort(lines, (a, b) -> a[0] - b[0]);
 
        // Find the number of total case
        long total_case = nCk(N, K);
 
        // Declare a multiset
        PriorityQueue<Integer> m = new PriorityQueue<>();
 
        // Loop till N
        for (int i = 0; i < N; i++) {
 
            // Check if smallest element is
            // smaller than lines[i]
            while (!m.isEmpty()
                   && (m.peek() < lines.get(i)[0])) {
 
                // Erase first element
                m.poll();
            }
 
            // Exclude the odd cases
            total_case -= nCk(m.size(), K - 1);
 
            // Modulus operation
            total_case += mod;
            total_case %= mod;
 
            // Insert into multiset
            m.add(lines.get(i)[1]);
        }
        System.out.println(total_case);
    }
 
    // Function to precompute
    // factorial and inverse
    static void preCompute()
    {
        long fact = 1;
 
        factorial[0] = 1;
        inverse[0] = 1;
 
        // Pre-compute factorial and inverse
        for (int i = 1; i < MAXN; i++) {
            fact = (fact * i) % mod;
            factorial[i] = fact;
 
            inverse[i] = power(factorial[i], mod - 2);
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 3, K = 2;
        ArrayList<int[]> lines = new ArrayList<>();
 
        // Function to pre-compute
        // factorial and inverse
        preCompute();
 
        lines.add(new int[] { 1, 3 });
        lines.add(new int[] { 4, 5 });
        lines.add(new int[] { 5, 7 });
 
        numberOfWays(lines, K, N);
    }
}
 
// This code is contributed by offbeat


Python3




# Python3 program to find Number of ways
# to choose K ersecting
# line segments on X-axis
 
import heapq as hq
 
mod = 1000000007
MAXN = 1001
factorial=[1]*MAXN; inverse=[1]*MAXN
 
# Function to find (a^b)%mod in log b
def power(a, b):
    res = 1
 
    # Till power becomes 0
    while (b > 0) :
 
        # If power is odd
        if (b % 2 == 1) :
            res = (res * a) % mod
         
        # Multiply base
        a = (a * a) % mod
 
        # Divide power by 1
        b >>= 1
     
 
    return res
 
 
# Function to find nCk
def nCk(n, k):
    # Base case
    if (k < 0 or k > n) :
        return 0
     
 
    # Apply formula to find nCk
    ans = factorial[n]
    ans = (ans * inverse[n - k]) % mod
    ans = (ans * inverse[k]) % mod
 
    return ans
 
 
# Function to find the number of ways
def numberOfWays(lines, K, N):
 
    # sort the given lines
    lines.sort()
 
    # Find the number of total case
    total_case = nCk(N, K)
 
    # Declare a heap
    m=[]
 
    # loop till N
    for i in range(N):
 
        # Check if smallest element is
        # smaller than lines[i]
        while (m and m[0] < lines[i][0]):
 
            # Erase first element
            hq.heappop(m)
         
        # Exclude the odd cases
        total_case -= nCk(len(m), K - 1)
 
        # Modulus operation
        total_case += mod
        total_case %= mod
 
        # Insert into heap
        hq.heappush(m,lines[i][1])
     
 
    print(total_case)
 
 
# Function to precompute
# factorial and inverse
def preCompute():
    global factorial
    fact = 1
 
    factorial[0] = 1
    inverse[0] = 1
 
    # Pre-compute factorial and inverse
    for i in range(1,MAXN) :
 
        fact = (fact * i) % mod
        factorial[i] = fact
        inverse[i] = power(factorial[i], mod - 2)
     
 
 
# Driver code
if __name__ == '__main__':
 
    N = 3; K = 2
    lines=[]
 
    # Function to pre-compute
    # factorial and inverse
    preCompute()
 
    lines.append((1, 3))
    lines.append((4, 5))
    lines.append((5, 7))
 
    numberOfWays(lines, K, N)


C#




// C// program to find Number of ways
// to choose K ersecting
// line segments on X-axis
using System;
using System.Collections.Generic;
 
namespace ConsoleApp1
{
  class Program
  {
    const int mod = 1000000007;
    const int MAXN = 1001;
    static long[] factorial = new long[MAXN];
    static long[] inverse = new long[MAXN];
 
    // Driver code
    static void Main(string[] args)
    {
      int N = 3, K = 2;
      List<(int, int)> lines = new List<(int, int)>();
 
      // Function to pre-compute
      // factorial and inverse
      PreCompute();
 
      lines.Add((1, 3));
      lines.Add((4, 5));
      lines.Add((5, 7));
      NumberOfWays(lines, K, N);
    }
 
 
    // Function to precompute
    // factorial and inverse
    static void PreCompute()
    {
      long fact = 1;
      factorial[0] = 1;
      inverse[0] = 1;
 
      // Pre-compute factorial and inverse
      for (int i = 1; i < MAXN; i++)
      {
        fact = (fact * i) % mod;
        factorial[i] = fact;
        inverse[i] = Power(factorial[i], mod - 2);
      }
    }
    // Function to find (a^b)%mod in log b
    static long Power(long a, int b)
    {
      long res = 1;
 
      // Till power becomes 0
      while (b > 0)
      {
 
        // If power is odd
        if (b % 2 == 1)
        {
          res = (res * a) % mod;
        }
 
        // Multiply base
        a = (a * a) % mod;
 
        // Divide power by 1
        b >>= 1;
      }
      return res;
    }
 
    // Function to find nCk
    static long NCk(int n, int k)
    {
      // Base case
      if (k < 0 || k > n)
      {
        return 0;
      }
 
      // Apply formula to find nCk
      long ans = factorial[n];
      ans = (ans * inverse[n - k]) % mod;
      ans = (ans * inverse[k]) % mod;
 
      return ans;
    }
 
    // Function to find the number of ways
    static void NumberOfWays(List<(int, int)> lines, int K, int N)
    {
 
      // sort the given lines
      lines.Sort();
 
      // Find the number of total case
      long total_case = NCk(N, K);
 
      // Declare a heap
      List<int> m = new List<int>();
 
      // loop till N
      for (int i = 0; i < N; i++)
      {
 
        // Check if smallest element is
        // smaller than lines[i]
        while (m.Count > 0 && m[0] < lines[i].Item1)
        {
          // Erase first element
          m.RemoveAt(0);
        }
 
        // Exclude the odd cases
        total_case -= NCk(m.Count, K - 1);
 
        // Modulus operation
        total_case += mod;
        total_case %= mod;
 
        // Insert into heap
        m.Add(lines[i].Item2);
      }
      Console.WriteLine(total_case);
    }
  }
}
 
// this code is contributed by Shivhack999


Output

2

Time Complexity: O(MAXN * log(MAXN) + N * log(N)).
Auxiliary Space: O(MAXN + N).



Similar Reads

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
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
Count ways to divide circle using N non-intersecting chord | Set-2
Given a number N. The task is to find the number of ways you can draw N chords in a circle with 2*N points such that no two chords intersect. Two ways are different if there exists a chord that is present in one way and not in other. As the answer could be large print it modulo 10^9+7. Examples: Input : N = 2 Output : 2 If points are numbered 1 to
8 min read
Count ways to split array into K non-intersecting subsets
Given an array, arr[] of size N and an integer K, the task is to split the array into K non-intersecting subsets such that union of all the K subsets is equal to the given array. Examples: Input : arr[]= {2, 3}, K=2Output: 4Explanations:Possible ways to partition the array into K(=2) subsets are:{ {{}, {2, 3}}, {{2}, {3}}, {{3}, {2}}, {{2, 3}, {}}
7 min read
Count ways to divide circle using N non-intersecting chords
Given a number N, find the number of ways you can draw N chords in a circle with 2*N points such that no 2 chords intersect. Two ways are different if there exists a chord which is present in one way and not in other.Examples: Input : N = 2 Output : 2 Explanation: If points are numbered 1 to 4 in clockwise direction, then different ways to draw cho
5 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
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
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
Number of ways to choose a pair containing an even and an odd number from 1 to N
Given a number N the task is to find the number of pairs containing an even and an odd number from numbers between 1 and N inclusive. Note: The order of numbers in the pair does not matter. That is (1, 2) and (2, 1) are the same. Examples: Input: N = 3 Output: 2 The pairs are (1, 2) and (2, 3).Input: N = 6 Output: 9 The pairs are (1, 2), (1, 4), (1
3 min read
Program to check if the points are parallel to X axis or Y axis
Given n points, we need to check if these n points are parallel to X axis or Y axis or to No axis. Examples: Input : x[] = {0, 0, 0, 0, 0| y[] = {9, 2, 1, 3, 4} Output : Parallel to Y Axis Input : x[] = {1, 2, 3| y[] = {9, 2, 1} Output : Not Parallel to X or Y Axis Approach To find the points parallel to X or Y axis just check if the points are sam
6 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
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
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
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
How to check if two given line segments intersect?
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,
13 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
Number of ways to choose elements from the array such that their average is K
Given an array arr[] of N integers and an integer K. The task is to find the number of ways to select one or more elements from the array such that the average of the selected integers is equal to the given number K. Examples: Input: arr[] = {7, 9, 8, 9}, K = 8 Output: 5 {8}, {7, 9}, {7, 9}, {7, 8, 9} and {7, 8, 9}Input: arr[] = {3, 6, 2, 8, 7, 6,
11 min read
Find Maximum number of intersecting points with at most K distance
Two players A and B are standing at starting point 0 of an infinite horizontal line. Player A is given an array with jumpA[] of size M and Player B is given an array with jumpB[] of size N. Both players can make jumps as: Player A can jump D distance in both directions (right or left), from its current point, such that D is present in jumpA[].Playe
8 min read
Count of Ways to Choose N People With at Least X Men and Y Women from P Men and Q Women | Set 2
Given integers N, P, Q, X, and Y, the task is to find the number of ways to form a group of N people having at least X men and Y women from P men and Q women, where (X + Y â‰Ī N, X â‰Ī P and Y â‰Ī Q). Examples: Input: P = 4, Q = 2, N = 5, X = 3, Y = 1Output: 6Explanation: Suppose given pool is {m1, m2, m3, m4} and {w1, w2}. Then possible combinations are
7 min read
Ways to choose three points with distance between the most distant points &lt;= L
Given a set of n distinct points x1, x2, x3... xn all lying on the X-axis and an integer L, the task is to find the number of ways of selecting three points such that the distance between the most distant points is less than or equal to L Note: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set of three points Exam
15+ min read
Count of ways to choose an integer that has exactly K larger elements in Array
Given an array arr[] of N distinct integers and a positive integer K, the task is to find the number of ways of choosing an integer X such that there are exactly K elements in the array that are greater than X. Examples: Input: arr[] = {1, 3, 4, 6, 8}, K = 2 Output: 3Explanation: X can be chosen as 4 or 5 Input: arr[] = {1, 2, 3}, K = 1 Output: 2Ex
9 min read
Ways to choose balls such that at least one ball is chosen
Given an integer N, the task is to find the ways to choose some balls out of the given N balls such that at least one ball is chosen. Since the value can be large so print the value modulo 1000000007.Example: Input: N = 2 Output: 3 The three ways are "*.", ".*" and "**" where '*' denotes the chosen ball and '.' denotes the ball which didn't get cho
3 min read
Count of ways to choose K elements from given Array with maximum sum
Given an array, arr[] of size N and an integer K, the task is to find the number of ways of selecting K array elements, such that the sum of these K elements is the maximum possible sum. Examples: Input: arr[] = {3, 1, 1, 2}, K = 3 Output: 2Explanation: The possible ways of selecting 3 elements are: {arr[0] (=3), arr[1] (=1), arr[2] (=1)}, the sum
8 min read
Count of ways to choose N people containing at least 4 boys and 1 girl from P boys and Q girls
Given integers N, P, and Q the task is to find the number of ways to form a group of N people having at least 4 boys and 1 girls from P boys and Q girls. Examples: Input: P = 5, Q = 2, N = 5Output: 10Explanation: Suppose given pool is {m1, m2, m3, m4, m5} and {w1, w2}. Then possible combinations are: m1 m2 m3 m4 w1m2 m3 m4 m5 w1m1 m3 m4 m5 w1m1 m2
6 min read
Count of All Possible Ways to Choose N People With at Least X Men and Y Women from P Men and Q Women
Given integers N, P, Q, X, and Y, the task is to find the number of ways to form a group of N people having at least X men and Y women from P men and Q women, where (X + Y â‰Ī N, X â‰Ī P and Y â‰Ī Q). Examples: Input: P = 4, Q = 2, N = 5, X = 3, Y = 1Output: 6Explanation: Suppose given pool is {m1, m2, m3, m4} and {w1, w2}. Then possible combinations are
7 min read