Program to find how many lines intersect in Python

Sometimes we need to find how many lines intersect within a given range. Given a list of lines in the form (m, c) representing y = mx + c, we can determine which lines intersect between x = l and x = h.

So, if the input is like input_list = [[4, 6],[-6, 10],[8, 12]], l = 0, h = 2, then the output will be 2.

x y l=0 h=2 y=4x+6 y=-6x+10 y=8x+12 intersection

In the given example, lines y = 4x + 6 and y = -6x + 10 intersect within the range x = 0 to x = 2. The algorithm counts how many lines participate in intersections.

Algorithm Steps

To solve this problem, we follow these steps ?

  • Calculate line segments by evaluating each line at x = l and x = h
  • Sort segments by their starting points
  • Use sweep line technique to detect intersections
  • Count lines that intersect with at least one other line

Example

Let us see the implementation to get better understanding ?

from collections import Counter

def solve(input_list, l, h):
    # Create segments: (y_at_l, y_at_h, line_index)
    seg = [(m * l + c, m * h + c, i) for i, (m, c) in enumerate(input_list)]
    seg.sort()
    
    # Track which lines intersect
    ans = [0 for _ in input_list]
    
    # Check for lines with same starting point
    c = Counter([x for x, y, i in seg])
    for (x, y, i) in seg:
        if c[x] > 1:
            ans[i] = 1
    
    # Forward sweep - find intersections
    max_c = -(10 ** 10)
    prv = -(10 ** 10)
    for (x, y, i) in seg:
        if x == prv:
            ans[i] = 1
        if y <= max_c:
            ans[i] = 1
        max_c = max(max_c, y)
        prv = x
    
    # Backward sweep - find remaining intersections
    min_c = 10 ** 10
    prv = 10 ** 10
    for (x, y, i) in seg[::-1]:
        if x == prv:
            ans[i] = 1
        if y >= min_c:
            ans[i] = 1
        min_c = min(min_c, y)
        prv = x
    
    return sum(ans)

# Test the function
lines = [[4, 6], [-6, 10], [8, 12]]
result = solve(lines, 0, 2)
print(f"Number of intersecting lines: {result}")
Number of intersecting lines: 2

How It Works

The algorithm transforms each line into a segment by evaluating y-values at x = l and x = h. It then uses a sweep line approach:

  • Forward sweep: Detects lines that cross over others from left to right
  • Backward sweep: Catches intersections missed in the forward pass
  • Same point check: Handles lines that start or end at the same y-value

Step-by-Step Example

# Line segments for x=0 to x=2
lines = [[4, 6], [-6, 10], [8, 12]]
l, h = 0, 2

for i, (m, c) in enumerate(lines):
    y_left = m * l + c   # y at x=0
    y_right = m * h + c  # y at x=2
    print(f"Line {i+1}: y={m}x+{c} -> segment ({y_left}, {y_right})")
Line 1: y=4x+6 -> segment (6, 14)
Line 2: y=-6x+10 -> segment (10, -2)
Line 3: y=8x+12 -> segment (12, 28)

Conclusion

This sweep line algorithm efficiently finds intersecting lines by transforming them into segments and detecting crossovers. The dual-direction sweep ensures all intersection patterns are captured within the given range.

Updated on: 2026-03-26T17:42:21+05:30

600 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements