You are given a 2D array lines[][], where each row [l, r] represents a horizontal line segment on the X-axis with endpoints at x = l and x = r (both inclusive). Return the maximum number of horizontal line segments that can be intersected by a single vertical line.
Examples:
Input: lines[][] = [[1,3], [2,3], [1,2], [4,4]]
Output: 3
Explanation: A vertical line at x = 2 intersects the segments [1, 3], [2, 3], and [1, 2].Input: lines[][] = [[1, 3], [5, 6], [3,4]]
Output: 2
Explanation: A vertical line at x = 3 intersects the segments [1, 3] and [3, 4].
This problem is mainly a variation of popular problem called Minimum Platforms.
Table of Content
[Naive Approach] Using Nested Loop – O(n * m) Time and O(1) Space
The idea is to try every possible vertical line and count how many horizontal segments it intersects.
We first find the minimum and maximum x-coordinates covered by the segments, then place a vertical line at every x-coordinate in this range.
For each position, we check which segments contain that x-coordinate and keep track of the maximum count obtained.
- Find the minimum and maximum x-coordinates among all the given line segments.
- Iterate over every x-coordinate from minX to maxX.
- For each x-coordinate, check every segment [l, r].
- If l <= x <= r, increment the intersection count.
- Update the maximum number of intersections for each vertical line.
- Return the maximum count obtained.
#include <bits/stdc++.h>
using namespace std;
int maxIntersections(vector<vector<int>> &lines)
{
int n = lines.size();
int maxInt = 0;
// Find the minimum and maximum x-coordinate
// among all the line segments.
int minX = INT_MAX, maxX = INT_MIN;
for (auto &line : lines)
{
minX = min(minX, line[0]);
maxX = max(maxX, line[1]);
}
// Try placing the vertical line at every
// possible x-coordinate.
for (int x = minX; x <= maxX; x++)
{
int cnt = 0;
// Count how many horizontal segments
// contain the current x-coordinate.
for (auto &line : lines)
{
// The vertical line at x intersects
// the segment if x lies in [l, r].
if (line[0] <= x && x <= line[1])
cnt++;
}
// Update the maximum number of intersections.
maxInt = max(maxInt, cnt);
}
return maxInt;
}
int main()
{
vector<vector<int>> lines = {{1, 3}, {5, 6}, {3, 4}};
cout << maxIntersections(lines) << endl;
return 0;
}
import java.util.*;
class GFG {
static int maxIntersections(int[][] lines)
{
int n = lines.length;
int maxInt = 0;
// Find the minimum and maximum x-coordinate
// among all the line segments.
int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE;
for (int[] line : lines) {
minX = Math.min(minX, line[0]);
maxX = Math.max(maxX, line[1]);
}
// Try placing the vertical line at every
// possible x-coordinate.
for (int x = minX; x <= maxX; x++) {
int cnt = 0;
// Count how many horizontal segments
// contain the current x-coordinate.
for (int[] line : lines) {
// The vertical line at x intersects
// the segment if x lies in [l, r].
if (line[0] <= x && x <= line[1])
cnt++;
}
// Update the maximum number of intersections.
maxInt = Math.max(maxInt, cnt);
}
return maxInt;
}
public static void main(String[] args)
{
int[][] lines = { { 1, 3 }, { 5, 6 }, { 3, 4 } };
System.out.println(maxIntersections(lines));
}
}
def maxIntersections(lines):
n = len(lines)
maxInt = 0
# Find the minimum and maximum x-coordinate
# among all the line segments.
minX = float('inf')
maxX = float('-inf')
for line in lines:
minX = min(minX, line[0])
maxX = max(maxX, line[1])
# Try placing the vertical line at every
# possible x-coordinate.
for x in range(minX, maxX + 1):
cnt = 0
# Count how many horizontal segments
# contain the current x-coordinate.
for line in lines:
# The vertical line at x intersects
# the segment if x lies in [l, r].
if line[0] <= x <= line[1]:
cnt += 1
# Update the maximum number of intersections.
maxInt = max(maxInt, cnt)
return maxInt
# Driver Code
if __name__ == "__main__":
lines = [[1, 3], [5, 6], [3, 4]]
print(maxIntersections(lines))
using System;
class GFG {
static int maxIntersections(int[][] lines)
{
int n = lines.Length;
int maxInt = 0;
// Find the minimum and maximum x-coordinate
// among all the line segments.
int minX = int.MaxValue, maxX = int.MinValue;
foreach(int[] line in lines)
{
minX = Math.Min(minX, line[0]);
maxX = Math.Max(maxX, line[1]);
}
// Try placing the vertical line at every
// possible x-coordinate.
for (int x = minX; x <= maxX; x++) {
int cnt = 0;
// Count how many horizontal segments
// contain the current x-coordinate.
foreach(int[] line in lines)
{
// The vertical line at x intersects
// the segment if x lies in [l, r].
if (line[0] <= x && x <= line[1])
cnt++;
}
// Update the maximum number of intersections.
maxInt = Math.Max(maxInt, cnt);
}
return maxInt;
}
public static void Main()
{
int[][] lines
= { new int[] { 1, 3 }, new int[] { 5, 6 },
new int[] { 3, 4 } };
Console.WriteLine(maxIntersections(lines));
}
}
function maxIntersections(lines)
{
let n = lines.length;
let maxInt = 0;
// Find the minimum and maximum x-coordinate
// among all the line segments.
let minX = Infinity;
let maxX = -Infinity;
for (let line of lines) {
minX = Math.min(minX, line[0]);
maxX = Math.max(maxX, line[1]);
}
// Try placing the vertical line at every
// possible x-coordinate.
for (let x = minX; x <= maxX; x++) {
let cnt = 0;
// Count how many horizontal segments
// contain the current x-coordinate.
for (let line of lines) {
// The vertical line at x intersects
// the segment if x lies in [l, r].
if (line[0] <= x && x <= line[1])
cnt++;
}
// Update the maximum number of intersections.
maxInt = Math.max(maxInt, cnt);
}
return maxInt;
}
// Driver Code
let lines = [ [ 1, 3 ], [ 5, 6 ], [ 3, 4 ] ];
console.log(maxIntersections(lines));
Output
2
Time complexity: O(n * m) where n is the size of list and m is the difference between the max and min x points.
[Better Approach] Using Sorting and Two Pointer – O(n * log n) Time and O(n) Space
The idea is to use sorting and two pointers to track how many line segments overlap at any point. We sort all starting and ending points separately and process them from left to right.
If the next segment starts before or exactly when the current segment ends, it adds to the number of active segments; otherwise, a segment has ended and the active count decreases.
By updating the maximum active count throughout the process, we get the maximum number of segments intersected by a single vertical line.
- Store all starting points and ending points of the segments in separate arrays.
- Sort both the starting and ending point arrays.
- Use two pointers i and j to traverse the sorted start and end points.
- If start[i] <= end[j], increment the active intersection count and move i.
- Otherwise, decrement the active count and move j.
- Update the maximum active count after every new segment starts and return it as the answer.
#include <bits/stdc++.h>
using namespace std;
int maxIntersections(vector<vector<int>> &lines)
{
int n = lines.size();
// Store all starting and ending points separately.
vector<int> start(n), end(n);
for (int i = 0; i < n; i++)
{
start[i] = lines[i][0];
end[i] = lines[i][1];
}
// Sort starting and ending points independently.
sort(start.begin(), start.end());
sort(end.begin(), end.end());
int i = 0, j = 0;
int intersect = 0, maxInter = 0;
// Sweep through the sorted starting and ending points.
while (i < n && j < n)
{
// If a line starts before or exactly when
// the current line ends, both lines overlap.
if (start[i] <= end[j])
{
intersect++;
// Update the maximum number of
// overlapping line segments.
maxInter = max(maxInter, intersect);
i++;
}
else
{
// A line has ended before the next line starts,
// so it is no longer part of the current overlap.
intersect--;
j++;
}
}
return maxInter;
}
int main()
{
vector<vector<int>> lines = {{1, 3}, {5, 6}, {3, 4}};
cout << maxIntersections(lines) << endl;
return 0;
}
import java.util.*;
class GFG {
static int maxIntersections(int[][] lines)
{
int n = lines.length;
// Store all starting and ending points separately.
int[] start = new int[n];
int[] end = new int[n];
for (int i = 0; i < n; i++) {
start[i] = lines[i][0];
end[i] = lines[i][1];
}
// Sort starting and ending points independently.
Arrays.sort(start);
Arrays.sort(end);
int i = 0, j = 0;
int intersect = 0, maxInter = 0;
// Sweep through the sorted starting and ending
// points.
while (i < n && j < n) {
// If a line starts before or exactly when
// the current line ends, both lines overlap.
if (start[i] <= end[j]) {
intersect++;
// Update the maximum number of
// overlapping line segments.
maxInter = Math.max(maxInter, intersect);
i++;
}
else {
// A line has ended before the next line
// starts, so it is no longer part of the
// current overlap.
intersect--;
j++;
}
}
return maxInter;
}
public static void main(String[] args)
{
int[][] lines = { { 1, 3 }, { 5, 6 }, { 3, 4 } };
System.out.println(maxIntersections(lines));
}
}
def maxIntersections(lines):
n = len(lines)
# Store all starting and ending points separately.
start = [0] * n
end = [0] * n
for i in range(n):
start[i] = lines[i][0]
end[i] = lines[i][1]
# Sort starting and ending points independently.
start.sort()
end.sort()
i = 0
j = 0
intersect = 0
maxInter = 0
# Sweep through the sorted starting and ending points.
while i < n and j < n:
# If a line starts before or exactly when
# the current line ends, both lines overlap.
if start[i] <= end[j]:
intersect += 1
# Update the maximum number of
# overlapping line segments.
maxInter = max(maxInter, intersect)
i += 1
else:
# A line has ended before the next line starts,
# so it is no longer part of the current overlap.
intersect -= 1
j += 1
return maxInter
# Driver Code
if __name__ == "__main__":
lines = [[1, 3], [5, 6], [3, 4]]
print(maxIntersections(lines))
using System;
class GFG {
static int maxIntersections(int[][] lines)
{
int n = lines.Length;
// Store all starting and ending points separately.
int[] start = new int[n];
int[] end = new int[n];
for (int k = 0; k < n; k++) {
start[k] = lines[k][0];
end[k] = lines[k][1];
}
// Sort starting and ending points independently.
Array.Sort(start);
Array.Sort(end);
int i = 0, j = 0;
int intersect = 0, maxInter = 0;
// Sweep through the sorted starting and ending
// points.
while (i < n && j < n) {
// If a line starts before or exactly when
// the current line ends, both lines overlap.
if (start[i] <= end[j]) {
intersect++;
// Update the maximum number of
// overlapping line segments.
maxInter = Math.Max(maxInter, intersect);
i++;
}
else {
// A line has ended before the next line
// starts, so it is no longer part of the
// current overlap.
intersect--;
j++;
}
}
return maxInter;
}
public static void Main()
{
int[][] lines
= { new int[] { 1, 3 }, new int[] { 5, 6 },
new int[] { 3, 4 } };
Console.WriteLine(maxIntersections(lines));
}
}
function maxIntersections(lines)
{
let n = lines.length;
// Store all starting and ending points separately.
let start = new Array(n);
let end = new Array(n);
for (let i = 0; i < n; i++) {
start[i] = lines[i][0];
end[i] = lines[i][1];
}
// Sort starting and ending points independently.
start.sort((a, b) => a - b);
end.sort((a, b) => a - b);
let i = 0, j = 0;
let intersect = 0, maxInter = 0;
// Sweep through the sorted starting and ending points.
while (i < n && j < n) {
// If a line starts before or exactly when
// the current line ends, both lines overlap.
if (start[i] <= end[j]) {
intersect++;
// Update the maximum number of
// overlapping line segments.
maxInter = Math.max(maxInter, intersect);
i++;
}
else {
// A line has ended before the next line starts,
// so it is no longer part of the current
// overlap.
intersect--;
j++;
}
}
return maxInter;
}
// Driver Code
let lines = [ [ 1, 3 ], [ 5, 6 ], [ 3, 4 ] ];
console.log(maxIntersections(lines));
Output
2
[Expected Approach] Using Line Sweep + Hash Map – O(n * log n) Time and O(n) Space
The idea is to use a sweep line and process only the important x-coordinates where the number of active line segments changes.
For each segment, we add +1 at its starting point and -1 at one position after its ending point, since both endpoints are inclusive. We store these changes in an ordered map and process them from left to right.
At each point, we update the number of active segments and keep track of the maximum value, which gives the maximum number of segments intersected by a single vertical line.
- Create an ordered map events to store changes in the number of active segments.
- For each segment [l, r], add +1 at l and -1 at r + 1.
- Process all events in increasing order of their x-coordinate.
- Maintain cnt as the current number of active line segments.
- Update maxCnt with the maximum value of cnt.
- Return maxCnt as the maximum number of intersections.
#include <bits/stdc++.h>
using namespace std;
int maxIntersections(vector<vector<int>> &lines)
{
map<int, int> events;
// Create events for each line segment.
for (auto &line : lines)
{
// Segment becomes active at its starting point.
events[line[0]]++;
// Segment becomes inactive after its ending point.
events[line[1] + 1]--;
}
int cnt = 0, maxCnt = 0;
// Process events in increasing order of x-coordinate.
for (auto &event : events)
{
cnt += event.second;
// Update the maximum number of active segments.
maxCnt = max(maxCnt, cnt);
}
return maxCnt;
}
int main()
{
vector<vector<int>> lines = {{1, 3}, {5, 6}, {3, 4}};
cout << maxIntersections(lines) << endl;
return 0;
}
import java.util.*;
class GFG {
static int maxIntersections(int[][] lines)
{
// Create an ordered map to store events.
TreeMap<Integer, Integer> events = new TreeMap<>();
// Create events for each line segment.
for (int[] line : lines) {
// Segment becomes active at its starting point.
events.put(line[0],
events.getOrDefault(line[0], 0) + 1);
// Segment becomes inactive after its ending
// point.
events.put(line[1] + 1,
events.getOrDefault(line[1] + 1, 0)
- 1);
}
int cnt = 0, maxCnt = 0;
// Process events in increasing order of
// x-coordinate.
for (Map.Entry<Integer, Integer> event :
events.entrySet()) {
cnt += event.getValue();
// Update the maximum number of active segments.
maxCnt = Math.max(maxCnt, cnt);
}
return maxCnt;
}
public static void main(String[] args)
{
int[][] lines = { { 1, 3 }, { 5, 6 }, { 3, 4 } };
System.out.println(maxIntersections(lines));
}
}
def maxIntersections(lines):
# Create a dictionary to store events.
events = {}
# Create events for each line segment.
for line in lines:
# Segment becomes active at its starting point.
events[line[0]] = events.get(line[0], 0) + 1
# Segment becomes inactive after its ending point.
events[line[1] + 1] = events.get(line[1] + 1, 0) - 1
cnt = 0
maxCnt = 0
# Process events in increasing order of x-coordinate.
for x in sorted(events):
cnt += events[x]
# Update the maximum number of active segments.
maxCnt = max(maxCnt, cnt)
return maxCnt
# Driver Code
if __name__ == "__main__":
lines = [
[1, 3],
[5, 6],
[3, 4]
]
print(maxIntersections(lines))
using System;
using System.Collections.Generic;
class GFG {
static int maxIntersections(int[][] lines)
{
// Create an ordered dictionary to store events.
SortedDictionary<int, int> events
= new SortedDictionary<int, int>();
// Create events for each line segment.
foreach(int[] line in lines)
{
// Segment becomes active at its starting point.
if (!events.ContainsKey(line[0]))
events[line[0]] = 0;
events[line[0]]++;
// Segment becomes inactive after its ending
// point.
int endPoint = line[1] + 1;
if (!events.ContainsKey(endPoint))
events[endPoint] = 0;
events[endPoint]--;
}
int cnt = 0, maxCnt = 0;
// Process events in increasing order of
// x-coordinate.
foreach(KeyValuePair<int, int> eventItem in events)
{
cnt += eventItem.Value;
// Update the maximum number of active segments.
maxCnt = Math.Max(maxCnt, cnt);
}
return maxCnt;
}
public static void Main()
{
int[][] lines
= { new int[] { 1, 3 }, new int[] { 5, 6 },
new int[] { 3, 4 } };
Console.WriteLine(maxIntersections(lines));
}
}
function maxIntersections(lines)
{
// Create a map to store events.
let events = new Map();
// Create events for each line segment.
for (let line of lines) {
// Segment becomes active at its starting point.
events.set(line[0], (events.get(line[0]) || 0) + 1);
// Segment becomes inactive after its ending point.
let endPoint = line[1] + 1;
events.set(endPoint,
(events.get(endPoint) || 0) - 1);
}
let cnt = 0;
let maxCnt = 0;
// Process events in increasing order of x-coordinate.
let sortedEvents =
[...events.entries() ].sort((a, b) => a[0] - b[0]);
for (let [x, value] of sortedEvents) {
cnt += value;
// Update the maximum number of active segments.
maxCnt = Math.max(maxCnt, cnt);
}
return maxCnt;
}
// Driver Code
let lines = [ [ 1, 3 ], [ 5, 6 ], [ 3, 4 ] ];
console.log(maxIntersections(lines));
Output
2