Online store~40 min2s · 256 MBtarget O(n log n) time, O(n) spacefenwick-tree
A warehouse floor plan is drawn on a grid of whole-number coordinates. Aisles run left to right, and cross-corridors run bottom to top. Each one is a straight segment of the plan.
A crossing is a point where a cross-corridor meets an aisle, and meeting at an end counts. Your team lead asks: "How many pairs of an aisle and a cross-corridor meet?" A plan can have 100,000 segments, so the count must be fast.
Write count_crossings(segments).
segments[i] = [x1, y1, x2, y2] is a segment. It is horizontal (an aisle) when y1 = y2 and x1 < x2. It is vertical (a corridor) when x1 = x2 and y1 < y2.Input: segments = [[0, 2, 6, 2], [3, 0, 3, 5], [1, 4, 5, 4], [5, 1, 5, 3], [6, 2, 6, 6]]
Output: 4There are two aisles: one at y = 2 from x = 0 to 6, and one at y = 4 from x = 1 to 5. There are three corridors, at x = 3, x = 5 and x = 6. Sweep from left to right:
| x | Event | Open aisles (their y) | Crossings counted |
|---|---|---|---|
| 0 | the aisle at y = 2 opens | 2 | 0 |
| 1 | the aisle at y = 4 opens | 2, 4 | 0 |
| 3 | the corridor from y = 0 to 5 asks | 2, 4 | 2 |
| 5 | the corridor from y = 1 to 3 asks, then the aisle at y = 4 closes | 2 | 1 |
| 6 | the corridor from y = 2 to 6 asks, then the aisle at y = 2 closes | none | 1 |
The corridor at x = 6 meets the aisle at y = 2 at its end, and that counts. The total is 2 + 1 + 1 = 4.
Input: segments = [[0, 0, 4, 0], [4, 0, 4, 3]]
Output: 1The corridor starts at the right end of the aisle, and meeting at an end counts.
Input: segments = [[0, 1, 5, 1], [0, 3, 5, 3]]
Output: 0Two aisles are not counted together, and there is no corridor.
1 ≤ len(segments) ≤ 100,0000 ≤ x1, y1, x2, y2 ≤ 1,000,000Testing every aisle against every corridor is up to 50,000 × 50,000 = 2.5 billion pairs, which is far too slow. The sweep has to keep the open aisles in a structure that answers how many have a height inside a range.