← MathWorks Interview Insights
The brute force answer basically writes itself, so of course they want you to do better.
Use a sweep-line algorithm with a Fenwick tree (BIT) to count intersections in O(n log n) time. Sort events by coordinate, process segment starts and ends, and for each segment, count active segments that intersect it. Handle edge cases by carefully ordering events at the same coordinate and deduplicating segments if necessary.
Pro tip: Clarify upfront whether duplicate segments should be counted as intersecting each other (they should, since they share all points). Also, mention that the sweep-line approach can be adapted to report the actual intersecting pairs if needed, but here we only need counts.
Confirm that segments are inclusive, intersections include touching at endpoints, and duplicate segments are considered intersecting. Discuss input size to justify O(n log n) over O(n^2).
Create events for each segment's start and end. Sort events by coordinate; for ties, process starts before ends to handle inclusive endpoints correctly. Use a Fenwick tree to maintain active segments' start points.
When processing a segment's start, query the Fenwick tree for active segments with start ≤ current start (since all active segments have end ≥ current start). When processing its end, remove its start from the tree.
For equal endpoints, ensure events are ordered so that a segment ending at x is removed after processing starts at x. For duplicate segments, treat them as separate; they will naturally count each other as intersecting.
State time O(n log n) due to sorting and Fenwick operations, space O(n). Walk through a small example with overlapping, touching, and duplicate segments to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.