LESSON 32 · INTERMEDIATE4 min read

Divide-and-Conquer Invariants: Inversion Counting and Closest Point Pairs

Leverage divide-and-conquer invariants to solve complex algorithmic challenges: counting array inversions in O(n log n) and finding closest point pairs in 2D space.

OpenJDK 21+ (LTS)Free to readModule 8 of 15
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Count array inversions in O(n log n) time by modifying the merge step of Merge Sort
  • Explain why inversion count measures the sortedness distance and similarity between ranked lists
  • Design an O(n log n) closest pair of points algorithm using 2D geometric strip filtering

01The Inversion Counting Problem and Ranking Metrics

An inversion in an array A is a pair of indices (i, j) such that i < j and A[i] > A[j]. The inversion count quantifies how far an array is from being completely sorted: a sorted array has exactly 0 inversions, while a reverse-sorted array of length n has the maximum possible n*(n-1)/2 inversions.

In recommendation engines and collaborative filtering, inversion counting is used to compute Kendall tau rank correlation—measuring the similarity between two users' preference rankings (e.g., movie ratings or search result preferences).

A naive brute-force loop comparing all index pairs requires O(n^2) comparisons. However, by observing that inversions can be partitioned into left-half inversions, right-half inversions, and split inversions spanning both halves, we can count all inversions in O(n log n) time during Merge Sort.

example.js☕Java
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02The Split Inversion Invariant Trace

Understanding why inversions += (mid - i + 1) works is central to divide-and-conquer correctness. Because both the left half [low..mid] and right half [mid+1..high] are already sorted, if aux[i] > aux[j], every element from index i through mid is also strictly greater than aux[j].

Consider Left = [3, 7, 9] and Right = [2, 5, 8]:

1. Compare 3 and 2: 3 > 2. Since Left is sorted, 7 and 9 are also > 2. Inversions added: (mid - i + 1) = 3 - 0 + 1 = 3 (pairs: (3,2), (7,2), (9,2)).

2. Compare 3 and 5: 3 <= 5. No inversion; take 3.

3. Compare 7 and 5: 7 > 5. Since Left is sorted, 9 is also > 5. Inversions added: 2 (pairs: (7,5), (9,5)).

In a single pass of the merge step, all split inversions are counted in O(n) work without nested loops.

03Closest Pair of Points in 2D Space

Another classic divide-and-conquer triumph is finding the pair of points with the minimum Euclidean distance among n points in a 2D plane. Brute-force pairwise distance checks require O(n^2) operations.

Using divide-and-conquer: First, sort points by x-coordinate. Split the plane with a vertical line x = mid into left and right subsets. Recursively find the minimum distance d_left and d_right, setting d = min(d_left, d_right).

The critical challenge is checking if there exists a split pair across the boundary with distance < d. We inspect a vertical strip of width 2d around the dividing line. Incredibly, geometric packing limits guarantee that for any point in the strip, at most 7 other points can lie within distance d! Sorting the strip by y-coordinate yields an overall O(n log n) runtime.

04Algorithmic Complexity Summary

Divide-and-conquer algorithms frequently reduce polynomial runtimes to optimal linearithmic bounds by exploiting sorted sub-structures during the combine phase:

Both algorithms achieve Theta(n log n) time and O(n) auxiliary space.

notes.txtPlain text
+-----------------------+-------------------+--------------------+------------------------+| Problem               | Brute Force Time  | D&C Optimal Time   | Recurrence Form        |+-----------------------+-------------------+--------------------+------------------------+| Inversion Counting    | O(n^2)            | O(n log n)         | T(n) = 2T(n/2) + O(n)  || Closest Pair of Points| O(n^2)            | O(n log n)         | T(n) = 2T(n/2) + O(n)  || Fast Fourier Transform| O(n^2)            | O(n log n)         | T(n) = 2T(n/2) + O(n)  || Strassen Matrix Mult  | O(n^3)            | O(n^2.807)         | T(n) = 7T(n/2) + O(n^2)|+-----------------------+-------------------+--------------------+------------------------+
LET IT CLICK

The ideas worth keeping.

  • Inversion counting quantifies array sortedness and powers recommendation ranking metrics.
  • During Merge Sort, split inversions are counted in O(1) per merge step using (mid - i + 1).
  • Geometric divide-and-conquer reduces 2D closest pair search from O(n^2) to O(n log n) via bounded strip filtering.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Given an array 1 20 6 4 5 manually lis

Given an array [1, 20, 6, 4, 5], manually list all inversions and compute the total inversion count.

your_turn_1.java☕Java
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.javaJava
// Inversion pairs:// (20, 6), (20, 4), (20, 5), (6, 4), (6, 5)// Total inversion count = 5

Compare each element with every element that appears after it.

02

Exercise 2: In the closest pair problem explain why at m

In the closest pair problem, explain why at most 7 points in the right half of the 2d-wide strip can be within distance d of a point in the left half.

your_turn_2.java☕Java
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.javaJava
// Any two points in the right strip must be separated by at least d (by inductive hypothesis).// In a rectangle of dimensions d by 2d, you can pack at most 8 points such that// no two points are closer than d (at most 4 in each d x d square).// Excluding the candidate point itself leaves at most 7 comparison targets.

Consider how many circles of diameter d can be packed into a d by 2d rectangle without overlapping centers.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01How does the merge step in Merge Sort count split inversions in O(n) time?
02What is the maximum number of inversions in an array of size n?
03What is the time complexity of the divide-and-conquer closest pair of points algorithm?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Given an array 1 20 6 4 5 manually lis

Given an array [1, 20, 6, 4, 5], manually list all inversions and compute the total inversion count.

EXPECTED OUTPUT
Build successful. (Java 15)
[Process exited normally]
Main.javaJava
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

MODULE 08 · PRACTICAL SELF-CHECK

Pause. Put the pieces together.

You’ve reached the end of Recursion & Backtracking: Subsets, Permutations & Pruning. Before moving on, use this task to check what you can do independently.

Implement state-space pruning with bitwise operations to solve combinatorial constraint problems.

Try it in your own environment and write down the result. This is a self-check; reading completion does not evaluate your code.

Review this module

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.