![]() |
VOOZH | about |
Given 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}, i.e. 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.
This problem is mainly a variation of popular problem called Minimum Platforms.
This approach is based on independently checking the count of every x-axis point that it lies across how many line segments.
2
Time complexity is O(n*m) where n is the size of list and m is the difference between the max and min x points.
In this approach, we first sort the start and end points of the line segments. We then use two pointers: one for the start points and one for the end points. If the start point is less than or equal to the end point, it means a new line is starting, so we increase the count of intersections. If the start point is greater than the end point, it means a line has ended, so we decrease the intersection count. At each step, we check and update the maximum number of intersections. This method efficiently tracks the intersections without having to check every single point on the x-axis.
3
Instead of checking all x-axis points, we focus only on the start and end points of the line segments. We use a map to track these points: incrementing the count when a line starts and decrementing it when a line ends. After processing all points, we simply check the map to find the point with the highest count, which gives the maximum number of intersections. This method is efficient as we only consider the relevant points.
2