Given x coordinates of N vertical lines (parallel to Y-axis) and M line segments extending from (x1, y1) to (x2, y2), the task is to find the total number of intersections of the line segments with the vertical lines.

Examples:

Input:_ N = 2, M = 1, lines[] = {-1, 1}, Segments[][4] = {0, 1, 2, 1}_

Output:_ 1_

Explanation:

There is only one point of intersection (1, 1)

Example 1 Image

Input:_ N = 4, M = 8, lines[] = {-5, -3, 2, 3}, segments[][4] = {{-2, 5, 5, -6}, {-5, -2, -3, -5}, {-2, 3, -6, 1}, {-1, -3, 4, 2}, { 2, 5, 2, 1}, { 4, 5, 4, -5}, {-2, -4, 5, 3}, { 1, 2, -2, 1}};_

Output:_ 8_

Explanation:

There are total of 8 intersections.

Dotted lines are the vertical lines.

A green circle denote a single point of intersection and

a green triangle denotes that two line segments

intersect same vertical line at that point.

Example 2 Image

Naive Approach:

The simplest approach is, for each query, check if a vertical line falls between the x-coordinates of the two points. Thus, each segment will have O(N) computational complexity.

Time complexity:_ O(N * M)_

Approach 2: The idea is to use Prefix Sum to solve this problem efficiently. Follow the steps below to solve the problem:

  • The first observation we can make is that the y-coordinates do not matter. Also, we can observe that just touching the vertical line does not count as an intersection.
  • First, compute a prefix array of the number of occurrences of vertical lines till now and then just subtract the number of occurrences till x2-1 (we don’t consider x2 as it just qualifies as touch and not as an intersection) from the number of occurrences till x1. So for each segment, computational complexity reduces to O(1).

Below is the implementation of the above approach.

#arrays #competitive programming #geometric #hash #cpp-map #geometric-lines

Count of intersections of M line segments with N vertical lines in XY plane
1.90 GEEK