Find the maximum number of intersections lines
Last Updated :
06 Dec, 2023
Given an N horizontal line segments are arranged on the X-axis of a 2D plane. The start and end point of each line segment is given in an Nx2 matrix lines[ ][ ], the task is to find the maximum number of intersections possible of any vertical line with the given N line segments.
Examples:
Input: N = 4, lines[][] = {{1, 3}, {2, 3}, {1, 2}, {4, 4}}
Output: 3
Explanation: A vertical line at X = 2 passes through {1, 3}, {2, 3}, {1, 2}, ie three of the given horizontal lines.
Input: N = 3, lines[][] = {{1, 3}, {5, 6}, {3, 4}}
Output: 2
Explanation: A vertical line at X = 3 passes through two of the given horizontal lines which are the maximum possible.
Approach: This can be solved with the following idea:
Using hashMap, we can determine the maximum value among all the points and return it as a answer.
Follow the steps mentioned below to implement the idea:
- Take the n, the number of horizontal lines, and matrix lines[][].
- Create a map to store the number of lines at each x-coordinate.
- Iterate through each line and update the map accordingly.
- Initialize variables to keep track of the maximum number of intersections and a sum to keep track of the number of lines at each x-coordinate.
- Iterate through the map and update the sum and maximum accordingly.
- Return the maximum number of intersections.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxIntersections(vector<vector< int > > lines, int N)
{
map< int , int > mp;
for ( int i = 0; i < lines.size(); i++) {
int a = lines[i][0];
int b = lines[i][1];
mp[a]++;
mp[b + 1]--;
}
int res = INT_MIN;
int sum = 0;
for ( auto it : mp) {
sum += it.second;
res = max(res, sum);
}
return res;
}
int main()
{
int n = 4;
vector<vector< int > > mat
= { { 1, 3 }, { 2, 3 }, { 1, 2 }, { 4, 4 } };
cout << maxIntersections(mat, n) << endl;
}
|
Java
import java.util.*;
public class MaxIntersections {
static int maxIntersections( int [][] lines, int N) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for ( int i = 0 ; i < N; i++) {
int a = lines[i][ 0 ];
int b = lines[i][ 1 ];
map.put(a, map.getOrDefault(a, 0 ) + 1 );
map.put(b + 1 , map.getOrDefault(b + 1 , 0 ) - 1 );
}
int res = Integer.MIN_VALUE;
int sum = 0 ;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
sum += entry.getValue();
res = Math.max(res, sum);
}
return res;
}
public static void main(String[] args) {
int n = 4 ;
int [][] mat = {
{ 1 , 3 }, { 2 , 3 }, { 1 , 2 }, { 4 , 4 }
};
System.out.println(maxIntersections(mat, n));
}
}
|
Python3
def max_intersections(lines, n):
mp = {}
for line in lines:
a = line[ 0 ]
b = line[ 1 ]
mp[a] = mp.get(a, 0 ) + 1
mp[b + 1 ] = mp.get(b + 1 , 0 ) - 1
res = float ( '-inf' )
sum_ = 0
for key, value in sorted (mp.items()):
sum_ + = value
res = max (res, sum_)
return res
n = 4
lines = [[ 1 , 3 ], [ 2 , 3 ], [ 1 , 2 ], [ 4 , 4 ]]
print (max_intersections(lines, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MaxIntersections(List< int []> lines)
{
List<Tuple< int , int >> events = new List<Tuple< int , int >>();
foreach ( int [] line in lines)
{
int a = line[0];
int b = line[1];
events.Add( new Tuple< int , int >(a, 1));
events.Add( new Tuple< int , int >(b + 1, -1));
}
events.Sort();
int res = 0;
int count = 0;
foreach ( var evt in events)
{
count += evt.Item2;
res = Math.Max(res, count);
}
return res;
}
static void Main()
{
List< int []> lines = new List< int []>
{
new int [] { 1, 3 },
new int [] { 2, 3 },
new int [] { 1, 2 },
new int [] { 4, 4 }
};
Console.WriteLine(MaxIntersections(lines));
}
}
|
Javascript
function maxIntersections(lines) {
const mp = {};
for (const line of lines) {
const a = line[0];
const b = line[1];
mp[a] = (mp[a] || 0) + 1;
mp[b + 1] = (mp[b + 1] || 0) - 1;
}
let res = Number.MIN_SAFE_INTEGER;
let sum = 0;
const sortedKeys = Object.keys(mp).sort((a, b) => a - b);
for (const key of sortedKeys) {
const value = mp[key];
sum += value;
res = Math.max(res, sum);
}
return res;
}
const n = 4;
const lines = [[1, 3], [2, 3], [1, 2], [4, 4]];
console.log(maxIntersections(lines));
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Approach 2: Using Sorting and Two pointers approach
Following steps to solve the problem:
1. Store the start points and end points in two separate vectors – one for start point and one for end point.
2. Now, sort the both vectors.
3. Take two pointer i and j and loop from both end using while loop.
4. Check the line starting before ending point ( start point[i]<=end point[j] ). So increment intersections and pointer i++ and also update ans.
5. Else the line ending before new line starting ( start point[i]>end point[j] ) . So decrement intersections– and increment j++;
6. Return the final answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxIntersections(vector<vector< int >> lines, int n) {
vector< int > start_lns(n);
vector< int > end_lns(n);
for ( int i=0;i<n;i++)
{
start_lns[i] = lines[i][0];
end_lns[i] = lines[i][1];
}
sort(start_lns.begin(), start_lns.end());
sort(end_lns.begin(), end_lns.end());
int i=0;
int j=0;
int intersxn=0;
int ans=INT_MIN;
while (i<n && j<n)
{
if (start_lns[i] <= end_lns[j])
{
intersxn++;
ans = max(ans, intersxn);
i++;
}
else
{
intersxn--;
j++;
}
}
return ans;
}
int main()
{
int n = 4;
vector<vector< int > > lines
= { { 1, 3 }, { 2, 3 }, { 1, 2 }, { 4, 4 } };
cout << maxIntersections(lines, n) << endl;
}
|
Java
import java.util.Arrays;
public class MaxIntersections {
static int maxIntersections( int [][] lines, int n) {
int [] startLines = new int [n];
int [] endLines = new int [n];
for ( int i = 0 ; i < n; i++) {
startLines[i] = lines[i][ 0 ];
endLines[i] = lines[i][ 1 ];
}
Arrays.sort(startLines);
Arrays.sort(endLines);
int i = 0 ;
int j = 0 ;
int intersections = 0 ;
int result = Integer.MIN_VALUE;
while (i < n && j < n) {
if (startLines[i] <= endLines[j]) {
intersections++;
result = Math.max(result, intersections);
i++;
}
else {
intersections--;
j++;
}
}
return result;
}
public static void main(String[] args) {
int n = 4 ;
int [][] lines = {
{ 1 , 3 },
{ 2 , 3 },
{ 1 , 2 },
{ 4 , 4 }
};
System.out.println(maxIntersections(lines, n));
}
}
|
Python3
def maxIntersections(lines, n):
start_lns = []
end_lns = []
for i in range (n):
start_lns.append(lines[i][ 0 ])
end_lns.append(lines[i][ 1 ])
start_lns.sort()
end_lns.sort()
i = 0
j = 0
intersxn = 0
ans = float ( '-inf' )
while (i<n and j<n):
if (start_lns[i] < = end_lns[j]):
intersxn + = 1
ans = max (ans, intersxn)
i + = 1
else :
intersxn - = 1
j + = 1
return ans
n = 4
lines = [ [ 1 , 3 ], [ 2 , 3 ], [ 1 , 2 ], [ 4 , 4 ] ]
print (maxIntersections(lines, n))
|
C#
using System;
using System.Collections.Generic;
class Program {
static int MaxIntersections(List< int []> lines, int n)
{
List< int > startLines = new List< int >(n);
List< int > endLines = new List< int >(n);
foreach ( var line in lines)
{
startLines.Add(line[0]);
endLines.Add(line[1]);
}
startLines.Sort();
endLines.Sort();
int i = 0;
int j = 0;
int intersections
= 0;
int answer = int .MinValue;
while (i < n && j < n) {
if (startLines[i] <= endLines[j]) {
intersections++;
answer = Math.Max(answer, intersections);
i++;
}
else {
intersections--;
j++;
}
}
return answer;
}
static void Main()
{
int n = 4;
List< int []> lines = new List< int []>{
new int [] { 1, 3 }, new int [] { 2, 3 },
new int [] { 1, 2 }, new int [] { 4, 4 }
};
Console.WriteLine(MaxIntersections(lines, n));
}
}
|
Javascript
function maxIntersections(lines, n) {
let startLines = new Array(n);
let endLines = new Array(n);
for (let i = 0; i < n; i++) {
startLines[i] = lines[i][0];
endLines[i] = lines[i][1];
}
startLines.sort((a, b) => a - b);
endLines.sort((a, b) => a - b);
let i = 0;
let j = 0;
let intersections = 0;
let ans = Number.MIN_SAFE_INTEGER;
while (i < n && j < n) {
if (startLines[i] <= endLines[j]) {
intersections++;
ans = Math.max(ans, intersections);
i++;
}
else {
intersections--;
j++;
}
}
return ans;
}
let n = 4;
let lines = [
[1, 3],
[2, 3],
[1, 2],
[4, 4]
];
console.log(maxIntersections(lines, n));
|
Time Complexity: O(N*log(N)), as sorting the vectors so time complexity is O(n).
Auxiliary Space: O(N), as taking the vector so space complexity is O(n).
Share your thoughts in the comments
Please Login to comment...