00:00

Problem Statement

Input/Output Examples

Visual Explanation

Because both halves are sorted during the merge, one comparison accounts for a whole group of inversions at once: mid - i + 1 of them.

Approaches

Merge sort counts inversions in O(n log n). The brute force checks every pair.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. Merge sort has log n levels of linear merging; the brute force examines n(n - 1) / 2 pairs.

Interview Tips and Recommended Approach

  • Use ≤ when merging. Equal values are not inversions.
  • Use long. The count can reach about n² / 2.
  • Explain the bulk count. It is the key insight that makes the algorithm fast.
  • Know the alternative. A Fenwick tree also counts inversions in O(n log n).

Recommended Approach: Count During Merge Sort

Why: it reuses a standard sorting algorithm and adds one line to count inversions in bulk, reaching O(n log n).