Problem
Suppose you are given two lists of n points, one list p1, p2, ..., pn
on the line y = 0 and the other list q1, q2, ..., qn
on the line y = 1. Imagine a set of n line segments connecting each point pi to qi. Write an algorithm to determine how many pairs of the line segments intersect.
Examples
Example 1:
|
|
Solution
Method 1 - Comparing points
First lets try to think, when the intersection will happen between 2 lines. Look at the cases below:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
- 🧺 Space complexity:
O(1)