Maximum number of intersections possible for any of the N given segments

Given an array arr[] consisting of N pairs of type {L, R}, each representing a segment on the X-axis, the task is to find the maximum number of intersections a segment has with other segments.
Examples:
Input: arr[] = {{1, 6}, {5, 5}, {2, 3}}
Output: 2
Explanation:
Below are the count of each segment that overlaps with the other segments:
- The first segment [1, 6] intersects with 2 segments [5, 5] and [2, 3].
- The second segment [5, 5] intersects with 1 segment [1, 6].
- The third segment [2, 3] intersects with 1 segment [1, 6].
Therefore, the maximum number of intersections among all the segment is 2.
Input: arr[][] = {{4, 8}, {3, 6}, {7, 11}, {9, 10}}
Output: 2
Naive Approach: The simplest approach to solve the given problem is to iterate over all segments and for each segment count the number of intersections by checking it with all other segments and then print the maximum among all the count of intersections obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach 1: The above approach can also be optimized based on the following observations:
- The above approach can be optimized by traversing each segment and calculating the number of segments that do not intersect the current segment using Binary Search and from that find the number of segments that intersect with the current segment
- Suppose [L, R] is the current segment and [P, Q] is another segment then, the segment [L, R] does not intersect with segment [P, Q] if Q < L or P > R.
- Suppose X is the number of the segments not intersecting with segment [L, R] then, the count of segments that intersects segment [L, R] = (N – 1 – X).
Follow the steps below to solve the problem:
- Store all the left points of segments in an array say L[] and all the right points of the segments in the array say R[].
- Sort both the arrays L[] and R[] in ascending order.
- Initialize a variable, say count as 0 to store the count of the maximum intersection a segment has.
- Traverse the array arr[] and perform the following steps:
- Calculate the number of segments left to the current segment {arr[i][0], arr[i][1]} using lower_bound() and store it in a variable say cnt.
- Calculate the number of segments right to the current segment {arr[i][0], arr[i][1]} using upper_bound() and increment the count of cnt by it.
- Update the value of count as the maximum of count and (N – cnt – 1).
- After completing the above steps, print the value of the count as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the maximum number// of intersections one segment has with// all the other given segmentsint maximumIntersections(int arr[][2],                         int N){    // Stores the resultant maximum count    int count = 0;Â
    // Stores the starting and the    // ending points    int L[N], R[N];Â
    for (int i = 0; i < N; i++) {        L[i] = arr[i][0];        R[i] = arr[i][1];    }Â
    // Sort arrays points in the    // ascending order    sort(L, L + N);    sort(R, R + N);Â
    // Traverse the array arr[]    for (int i = 0; i < N; i++) {        int l = arr[i][0];        int r = arr[i][1];Â
        // Find the count of segments        // on left of ith segment        int x = lower_bound(R, R + N, l) - R;Â
        // Find the count of segments        // on right of ith segment        int y = N - (upper_bound(L, L + N, r) - L);Â
        // Find the total segments not        // intersecting with the current        // segment        int cnt = x + y;Â
        // Store the count of segments        // that intersect with the        // ith segment        cnt = N - cnt - 1;Â
        // Update the value of count        count = max(count, cnt);    }Â
    // Return the resultant count    return count;}Â
// Driver Codeint main(){Â Â Â Â int arr[][2] = { { 1, 6 }, { 5, 5 }, { 2, 3 } };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << maximumIntersections(arr, N);Â
    return 0;} |
Java
// java program for the above approachimport java.util.*; Â
class GFG {static int lower_bound(int[] a, int low, int high, long element)    {        while(low < high)        {            int middle = low + (high - low) / 2;            if(element > a[middle])                low = middle + 1;            else                high = middle;        }        return low;    }static int maximumIntersections(int [][]arr,                         int N){    // Stores the resultant maximum count    int count = 0;       // Stores the starting and the    // ending points    int[] L = new int[N];    int[] R = new int[N];    for (int i = 0; i < N; i++) {        L[i] = arr[i][0];        R[i] = arr[i][1];    }       // Sort arrays points in the    // ascending order    Arrays.sort(L);    Arrays.sort(R);       // Traverse the array arr[]    for (int i = 0; i < N; i++) {        int l = arr[i][0];        int r = arr[i][1];           // Find the count of segments        // on left of ith segment        int x = lower_bound(L, 0,N, l);           // Find the count of segments        // on right of ith segment        int y = N-lower_bound(R, 0,N, r+1);           // Find the total segments not        // intersecting with the current        // segment        int cnt = x + y;               // Store the count of segments        // that intersect with the        // ith segment        cnt = N - cnt - 1;           // Update the value of count        count = Math.max(count, cnt);    }       // Return the resultant count    return count;}Â
// Driver Codepublic static void main(String[] args) { Â Â Â Â int arr[][] = { { 1, 6 }, { 5, 5 }, { 2, 3 } };Â Â Â Â int N = arr.length;Â Â Â Â System.out.println(maximumIntersections(arr, N));}}Â
// This code is contributed by stream_cipher. |
Python3
# Python 3 program for the above approachfrom bisect import bisect_left, bisect_rightÂ
Â
def lower_bound(a, low, high, element):Â
    while(low < high):Â
        middle = low + (high - low) // 2        if(element > a[middle]):            low = middle + 1        else:            high = middleÂ
    return lowÂ
Â
# Function to find the maximum number# of intersections one segment has with# all the other given segmentsdef maximumIntersections(arr,                         N):Â
    # Stores the resultant maximum count    count = 0Â
    # Stores the starting and the    # ending points    L = [0]*N    R = [0]*NÂ
    for i in range(N):        L[i] = arr[i][0]        R[i] = arr[i][1]Â
    # Sort arrays points in the    # ascending order    L.sort()    R.sort()Â
    # Traverse the array arr[]    for i in range(N):        l = arr[i][0]        r = arr[i][1]Â
        # Find the count of segments        # on left of ith segment        x = lower_bound(L, 0, N, l)Â
        # Find the count of segments        # on right of ith segment        y = N-lower_bound(R, 0, N, r+1)Â
        # Find the total segments not        # intersecting with the current        # segment        cnt = x + yÂ
        # Store the count of segments        # that intersect with the        # ith segment        cnt = N - cnt - 1Â
        # Update the value of count        count = max(count, cnt)Â
    # Return the resultant count    return countÂ
# Driver Codeif __name__ == "__main__":Â
    arr = [[1, 6], [5, 5], [2, 3]]    N = len(arr)    print(maximumIntersections(arr, N))Â
    # This code is contributed by ukasp. |
C#
// C# program for the above approachusing System;using System.Collections.Generic; Â
class GFG{     static int lower_bound(int[] a, int low,                        int high, long element){    while(low < high)    {        int middle = low + (high - low) / 2;                 if (element > a[middle])            low = middle + 1;        else            high = middle;    }    return low;}Â
static int maximumIntersections(int [,]arr,                                int N){         // Stores the resultant maximum count    int count = 0;       // Stores the starting and the    // ending points    int[] L = new int[N];    int[] R = new int[N];    for(int i = 0; i < N; i++)     {        L[i] = arr[i, 0];        R[i] = arr[i, 1];    }       // Sort arrays points in the    // ascending order    Array.Sort(L);    Array.Sort(R);       // Traverse the array arr[]    for(int i = 0; i < N; i++)    {        int l = arr[i, 0];        int r = arr[i, 1];           // Find the count of segments        // on left of ith segment        int x = lower_bound(L, 0, N, l);           // Find the count of segments        // on right of ith segment        int y = N-lower_bound(R, 0, N, r + 1);           // Find the total segments not        // intersecting with the current        // segment        int cnt = x + y;               // Store the count of segments        // that intersect with the        // ith segment        cnt = N - cnt - 1;           // Update the value of count        count = Math.Max(count, cnt);    }         // Return the resultant count    return count;}Â
// Driver Codepublic static void Main() { Â Â Â Â int [,]arr = new int[3, 2]{ { 1, 6 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 5, 5 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 2, 3 } };Â Â Â Â int N = 3;Â Â Â Â Â Â Â Â Â Console.Write(maximumIntersections(arr, N));}}Â
// This code is contributed by SURENDRA_GANGWAR |
Javascript
<script>Â
// Javascript program for the above approachfunction lower_bound(a, low, high, element){    while(low < high)    {        let middle = low + Math.floor(            (high - low) / 2);                     if (element > a[middle])            low = middle + 1;        else            high = middle;    }    return low;}Â
// Function to find the maximum number// of intersections one segment has with// all the other given segmentsfunction maximumLetersections(arr, N){         // Stores the resultant maximum count    let count = 0;        // Stores the starting and the    // ending points    let L = Array.from({length: N}, (_, i) => 0);    let R = Array.from({length: N}, (_, i) => 0);    for(let i = 0; i < N; i++)    {        L[i] = arr[i][0];        R[i] = arr[i][1];    }        // Sort arrays points in the    // ascending order    L.sort();    R.sort();        // Traverse the array arr[]    for(let i = 0; i < N; i++)     {        let l = arr[i][0];        let r = arr[i][1];            // Find the count of segments        // on left of ith segment        let x = lower_bound(L, 0, N, l);            // Find the count of segments        // on right of ith segment        let y = N-lower_bound(R, 0, N, r + 1);            // Find the total segments not        // intersecting with the current        // segment        let cnt = x + y;                // Store the count of segments        // that intersect with the        // ith segment        cnt = N - cnt - 1;            // Update the value of count        count = Math.max(count, cnt);    }        // Return the resultant count    return count;}Â
// Driver Codelet arr = [ [ 1, 6 ], [ 5, 5 ], [ 2, 3 ] ];let N = arr.length;Â
document.write(maximumLetersections(arr, N));Â
// This code is contributed by susmitakundugoaldangaÂ
</script> |
2
Time Complexity: O(N*log N)Â
Auxiliary Space: O(N)
Efficient Approach 2: Â Using hashmap.
Intuition: First we define a haspmap. Then traverse over the array and increment the count of L and decrement the count of (R+1) in the map( because we can draw vertical line through all the points within the range of L and R (both including) so we decrement the count of (R+1) point).  At any point in time, the sum of values (total  sum from start till point) in the map will give us the number of overlapping present at the point. We can then find the maximum of this sum, which will give us the maximum number of overlapping possible.
Follow the steps below to solve the problem:
- define a haspmap .
- Traverse over the array and increment the count of L and decrement the count of (R+1) int the map.
- Iterate over the map and keep track of the maximum sum seen so far. This maximum sum will give us the maximum number of the overlapping present.
- return the maximum sum.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the maximum number// of intersections one segment has with// all the other given segmentsint maximumIntersections(int arr[][2],                        int N){    // Stores the resultant maximum count    int count = 0;Â
    // create a map    map<int , int> pointCount;     // traverse the array    for(int i=0; i<N; i++){         // increment the count of L    pointCount[arr[i][0]]++;         // decrement the count of (R+1)    pointCount[arr[i][1] + 1]--;         }    // store the current sum    int currSum=0;    for( auto it : pointCount){         currSum += it.second;         // taking the max of sum    count= max(count, currSum);         }         // Return the resultant count    return count;}Â
// Driver Codeint main(){Â Â Â Â int arr[][2] = { { 1, 6 }, { 5, 5 }, { 2, 3 } };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << maximumIntersections(arr, N);Â
    return 0;} |
Java
import java.util.*;Â
class GFG {    // Function to find the maximum number of intersections    // one segment has with all the other given segments    public static int maximumIntersections(int[][] arr, int N) {        // Stores the resultant maximum count        int count = 0;Â
        // Create a TreeMap        TreeMap<Integer, Integer> pointCount = new TreeMap<>();Â
        // Traverse the array        for (int i = 0; i < N; i++) {            // Increment the count of L            pointCount.put(arr[i][0], pointCount.getOrDefault(arr[i][0], 0) + 1);Â
            // Decrement the count of (R+1)            pointCount.put(arr[i][1] + 1, pointCount.getOrDefault(arr[i][1] + 1, 0) - 1);        }Â
        // Store the current sum        int currSum = 0;        for (int value : pointCount.values()) {            currSum += value;Â
            // Taking the max of sum            count = Math.max(count, currSum);        }Â
        // Return the resultant count        return count;    }Â
    // Driver Code    public static void main(String[] args) {        int[][] arr = {{1, 6}, {5, 5}, {2, 3}};        int N = arr.length;        System.out.println(maximumIntersections(arr, N));    }} |
Python3
def maximumIntersections(arr, N):    count = 0    pointCount = {} # Create a dictionary to store point counts         # Traverse the array of segments    for i in range(N):        # Increment the count of the left endpoint of the segment        pointCount[arr[i][0]] = pointCount.get(arr[i][0], 0) + 1                 # Decrement the count of the right endpoint of the segment + 1        pointCount[arr[i][1] + 1] = pointCount.get(arr[i][1] + 1, 0) - 1         currSum = 0    # Iterate through the sorted points and their counts    for point, val in sorted(pointCount.items()):        currSum += val        count = max(count, currSum) # Update the maximum intersection count         return countÂ
# Driver Codeif __name__ == "__main__":Â Â Â Â arr = [[1, 6], [5, 5], [2, 3]]Â Â Â Â N = len(arr)Â Â Â Â result = maximumIntersections(arr, N)Â Â Â Â print(result) |
C#
using System;using System.Collections.Generic;Â
class GFG{    // Function to find the maximum number of intersections     // one segment has with all the other given segments    public static int MaximumIntersections(int[][] arr, int N)    {        // Stores the resultant maximum count        int count = 0;Â
        // Create a SortedDictionary        SortedDictionary<int, int> pointCount = new SortedDictionary<int, int>();Â
        // Traverse the array        for (int i = 0; i < N; i++)        {            // Increment the count of L            if (!pointCount.ContainsKey(arr[i][0]))                pointCount[arr[i][0]] = 1;            else                pointCount[arr[i][0]]++;Â
            // Decrement the count of (R+1)            if (!pointCount.ContainsKey(arr[i][1] + 1))                pointCount[arr[i][1] + 1] = -1;            else                pointCount[arr[i][1] + 1]--;        }Â
        // Store the current sum        int currSum = 0;        foreach (var value in pointCount.Values)        {            currSum += value;Â
            // Taking the max of sum            count = Math.Max(count, currSum);        }Â
        // Return the resultant count        return count;    }Â
    // Driver Code    public static void Main(string[] args)    {        int[][] arr = { new int[] { 1, 6 }, new int[] { 5, 5 }, new int[] { 2, 3 } };        int N = arr.Length;        Console.WriteLine(MaximumIntersections(arr, N));    }} |
Javascript
function MaximumIntersections(arr) {  // Create an array to store point counts  let pointCount = [];Â
  // Traverse the array  for (let i = 0; i < arr.length; i++) {    // Increment the count of L    if (!pointCount[arr[i][0]]) {      pointCount[arr[i][0]] = 1;    } else {      pointCount[arr[i][0]]++;    }Â
    // Decrement the count of (R+1)    if (!pointCount[arr[i][1] + 1]) {      pointCount[arr[i][1] + 1] = -1;    } else {      pointCount[arr[i][1] + 1]--;    }  }Â
  // Store the current sum  let currSum = 0;  let count = 0;  for (let i = 0; i < pointCount.length; i++) {    if (pointCount[i] !== undefined) {      currSum += pointCount[i];Â
      // Taking the max of sum      count = Math.max(count, currSum);    }  }Â
  // Return the resultant count  return count;}Â
// Driver Codeconst arr = [[1, 6], [5, 5], [2, 3]];console.log(MaximumIntersections(arr)); // Output: 2 |
2
Time Complexity: O(N*log N)Â ( insertion in a map takes (log N) and total N number of points)
Auxiliary Space: O(N) (size of map)
Approach 3: Sweep Line Algorithm
- This is most efficient approach that can solve the problem in O(N log N) time complexity.
Idea: Sort the segments by their left endpoint and then process them on by on using sweep line that moves from left
to right. Then maintain a set of segments that intersect with the sweep line, and update the maximum number of
intersections at each step.
Follow the steps below to solve the problem:
- read the segments from the input and store them in a vector of pair.
- Each pair represents a segment, with the first element being the left endpoint and the second element being the right endpoint.
- create two events (one for the left and one for the right endpoint).
- each event is respresnted as pair of form {x coordinates, +1 or -1}, where +1 or -1 indicates the event is left or right endpoint of the segment.
- store all the events in a single vector.
- Traverse the events : initialize a count of the segment intersecting the sweep line to 0, and initialize a variable to keep track of the maximum no. of intersections seen so far.
- loop through all the events in the sorted order, and for every event:
1. if event is a left event, then increment count.
2. if the event is right event, decrement the count.
3. update the maximum no. of intersections seen so far by taking maximum current count and maximum  so far. - Return the maximum number of intersections.Â
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std;Â
// Comparison function for sorting eventsbool cmp(pair<int, int>& a, pair<int, int>& b){Â Â Â Â return a.first < b.first;}Â
// Function to find the maximum number of intersectionsint maxIntersections(vector<pair<int, int> >& segments){Â Â Â Â int n = segments.size();Â
    vector<pair<int, int> > events;    for (int i = 0; i < n; i++) {        events.push_back({ segments[i].first, 1 });        events.push_back({ segments[i].second, -1 });    }Â
    // Sort the events    sort(events.begin(), events.end(), cmp);Â
    // Traverse the events and keep track of the maximum    // number of intersections    int ans = 0, cnt = 0;    for (int i = 0; i < 2 * n; i++) {        cnt += events[i].second;        ans = max(ans, cnt);    }    // Return the maximum number of intersections    return ans;}Â
int main(){    vector<pair<int, int> > segments        = { { 1, 6 }, { 5, 5 }, { 2, 3 } };    cout << maxIntersections(segments) << endl;Â
    return 0;} |
Java
import java.util.*;import java.util.AbstractMap.SimpleEntry;Â
// Comparison function for sorting eventsclass EventComparator implements Comparator<AbstractMap.SimpleEntry<Integer, Integer>> {    @Override    public int compare(AbstractMap.SimpleEntry<Integer, Integer> a, AbstractMap.SimpleEntry<Integer, Integer> b) {        return Integer.compare(a.getKey(), b.getKey());    }}Â
public class MaximumIntersections {Â
    // Function to find the maximum number of intersections    public static int maxIntersections(List<AbstractMap.SimpleEntry<Integer, Integer>> segments) {        int n = segments.size();Â
        List<AbstractMap.SimpleEntry<Integer, Integer>> events = new ArrayList<>();        for (int i = 0; i < n; i++) {            events.add(new AbstractMap.SimpleEntry<>(segments.get(i).getKey(), 1));            events.add(new AbstractMap.SimpleEntry<>(segments.get(i).getValue(), -1));        }Â
        // Sort the events        Collections.sort(events, new EventComparator());Â
        // Traverse the events and keep track of the maximum        // number of intersections        int ans = 0, cnt = 0;        for (int i = 0; i < 2 * n; i++) {            cnt += events.get(i).getValue();            ans = Math.max(ans, cnt);        }        // Return the maximum number of intersections        return ans;    }Â
    public static void main(String[] args) {        List<AbstractMap.SimpleEntry<Integer, Integer>> segments = new ArrayList<>();        segments.add(new AbstractMap.SimpleEntry<>(1, 6));        segments.add(new AbstractMap.SimpleEntry<>(5, 5));        segments.add(new AbstractMap.SimpleEntry<>(2, 3));Â
        int maxIntersect = maxIntersections(segments);        System.out.println(maxIntersect);    }} |
Output:
2
Time Complexity: O(n log n), where n is the number of segments.
Auxiliary Space: O(n log n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



