Question

# Consider n chords on a circle, each defined by its endpoints. Describe an O(n lg n)-time algorithm to determine the number of pairs of chords that intersect inside the circle. (For example, if the n chords are all diameters that meet at the center, then the correct answer is$(^n_2)$. ). Assume that no two chords share an endpoint.

Solution

Verified
Step 1
1 of 3

We imagine that we are given $2n$ points on the circle, labeled $\qty[1 \cdots 2n]$ in clockwise order of appearance in the circle, where the starting point can be chosen arbitrarily, i.e. north pole of the circle.

Furthermore, we are given the set of $n$ chords determined by the endpoints from $\qty[1 \cdots 2n]$. It is assumed that no two chords share an endpoint. We can assume that we have a mapping $f$ that produces for each point on the circle its counterpart that makes a chord in constant time. E.g. if $f(2) = 6$, that means that 2nd and 6th point encountered on the tour around the circle, starting from the north pole and going clockwise, make a chord. Of course, $f(6) = 2$ in this case as well.

Now produce the array $A\qty[1 \cdots 2n]$ as follows. First point on the circle (again - starting from the north pole and going clockwise), denoted with 1, is given a $\textit{key}$, $\textbf{1}$. Its chord-generating-counterpart, point $f(1)$, is given the same key. Proceed to the next keyless point, which can be either 3 or 2, depending on whether $f(1) = 2$ or not, and give it the next key $\textbf{2}$. Give the same key to its chord-generating counterpart and continue.

For example, array $A$ could begin like this:

$\qty[1, 2, 3, 2, 4, 1, 3, 4]$

Notice that chords are $f(1) = 6$, $f(2) = 4$, $f(3) = 7$, $f(5) = 8$.

Most importantly, you might notice that $\textbf{number of inversions in this array is the number of chords that are intersecting inside the circle!}$

## Recommended textbook solutions #### Computer Organization and Design MIPS Edition: The Hardware/Software Interface

5th EditionDavid A. Patterson, John L. Hennessy
220 solutions #### Fundamentals of Database Systems

7th EditionRamez Elmasri, Shamkant B. Navathe
687 solutions #### Introduction to Algorithms

3rd EditionCharles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen
726 solutions #### Introduction to the Theory of Computation

3rd EditionMichael Sipser
389 solutions