1388. Crossing Chords
Points numbered 1 to 2n sit in order around a circle. The array endpoints is a permutation of those numbers, and entries 2i and 2i+1 (0-indexed) are the two ends of chord i, drawn as a straight line across the circle. The two ends of a chord may appear in either order.
Two chords cross exactly when one end of one chord lies strictly between the two ends of the other, measured along the numbering, and its other end lies outside them. Return the number of unordered pairs of chords that cross, as a 64-bit integer. The answer can reach about 5 * 10^9, and comparing every pair is too slow at the upper limit, so aim for O(n log n) time and O(n) extra space.
Example 1
- Input:
- endpoints = [1,3,2,4]
- Output:
- 1
- Explanation:
Chord 1-3 and chord 2-4 interleave, so the single pair crosses.
Example 2
- Input:
- endpoints = [1,4,2,5,3,6]
- Output:
- 3
- Explanation:
Chords 1-4, 2-5 and 3-6 pairwise interleave, giving 3 crossing pairs.
Example 3
- Input:
- endpoints = [1,6,2,5,3,4]
- Output:
- 0
- Explanation:
The chords are nested inside one another, so no pair crosses.
Constraints
1 ≤ n ≤ 105; endpoints.length == 2n; endpoints is a permutation of 1..2n.
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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)