1421. Crossing Segments Count
A city map shows east-west streets and north-south streets. Street horizontals[i] = [y, x, len] runs from (x, y) to (x + len, y), and street verticals[j] = [x, y, len] runs from (x, y) to (x, y + len). A length of 0 makes the street a single point.
Return the number of pairs (horizontal street, vertical street) that share at least one point, endpoints included, as a 64-bit integer. Streets of the same orientation never count against each other, and identical streets are counted separately. Both lists can hold 10^5 streets and the answer can exceed 10^9, so a pairwise test is too slow; aim for O(n log n) time and O(n) space.
Example 1
- Input:
- horizontals = [[2,0,4]], verticals = [[1,0,3],[5,0,5]]
- Output:
- 1
- Explanation:
The street at x = 1 reaches y = 2 and meets the horizontal street, while the street at x = 5 lies beyond its right end, so the answer is 1.
Example 2
- Input:
- horizontals = [[0,0,2]], verticals = [[2,0,0]]
- Output:
- 1
- Explanation:
The vertical street is the single point (2, 0), which is the right endpoint of the horizontal street, so they touch.
Example 3
- Input:
- horizontals = [[1,0,4],[2,0,4]]verticals = [[1,0,4],[3,0,4]]
- Output:
- 4
- Explanation:
Every horizontal street crosses every vertical street, giving 2 * 2 = 4 pairs.
Constraints
1 ≤ horizontals.length, verticals.length ≤ 105; 0 ≤ every coordinate and len ≤ 106.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,800 msC++ 1,200 msJava 2,400 msJavaScript 2,400 msTypeScript 2,400 ms
Expected complexity
- Time
- O((H + V) log (H + V))
- Space
- O(H + V)