1243. Parallel Segment Pairs
A drawing tool needs to know how many pairs of line segments run in the same direction. Each row of segments is [x1, y1, x2, y2], the two endpoints of one segment. Two segments are parallel when their direction vectors (x2 - x1, y2 - y1) point along the same line, in either sense. Segments that lie on one line, or that overlap, are still parallel.
Return, as a long, the number of index pairs i < j whose segments are parallel. A segment whose two endpoints coincide has no direction and belongs to no pair. Reduce each direction by the gcd of its two parts and fix its sign so it can serve as a hash key. The intended solution runs in O(n log C) time and O(n) space, where n is the length of segments and C is the largest coordinate magnitude.
Example 1
- Input:
- segments = [[0,0,2,2],[1,1,3,3],[0,0,1,2]]
- Output:
- 1
- Explanation:
Segments 0 and 1 both run along (1, 1) and overlap, so they are parallel, while segment 2 runs along (1, 2).
Example 2
- Input:
- segments = [[0,0,4,0],[0,1,4,1],[5,5,5,5],[3,3,3,3]]
- Output:
- 1
- Explanation:
The two horizontal segments are parallel, and the two zero-length segments belong to no pair.
Example 3
- Input:
- segments = [[0,0,1,0],[0,0,0,1],[0,0,1,1]]
- Output:
- 0
- Explanation:
The directions (1, 0), (0, 1) and (1, 1) are all different, so no pair is parallel.
Constraints
-
1 ≤ segments.length ≤ 1000 -
segments[i].length == 4 -
-104 ≤ coordinate ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log C)
- Space
- O(n)