1. Base case
A single element is already sorted with zero inversions.
if (arr.length <= 1) return [arr, 0]Typorithm · hard
Step 1 of 8 · intro card
Divide & Conquer
Augment merge sort: when a right element is placed early, all leftover left elements are inversions.
An inversion is a pair i < j where nums[i] > nums[j].
Counting within each half is recursive; the clever part is counting cross-half inversions during the merge.
Each time a right element jumps ahead of remaining left elements, those left elements are all inversions with it.
Inversions split into left, right, cross.
Cross pairs are counted at the merge.
count += left.length - i.
function countInversions(nums) {
function sortCount(arr) {
if (arr.length <= 1) return [arr, 0];
const mid = Math.floor(arr.length / 2);
const [left, leftCount] = sortCount(arr.slice(0, mid));
const [right, rightCount] = sortCount(arr.slice(mid));
const merged = [];
let i = 0;
let j = 0;
let count = leftCount + rightCount;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged.push(left[i]);
i += 1;
} else {
merged.push(right[j]);
j += 1;
count += left.length - i;
}
}
return [merged.concat(left.slice(i), right.slice(j)), count];
}
return sortCount(nums)[1];
}Connect each part of the code to the concept before you type.
A single element is already sorted with zero inversions.
if (arr.length <= 1) return [arr, 0]Split the array into two halves to count recursively.
const mid = Math.floor(arr.length / 2)Start with inversions counted within each half.
let count = leftCount + rightCountWhen a right value is smaller, every remaining left value forms an inversion with it.
count += left.length - iAppend whatever remains of either half to the merged result.
merged.concat(left.slice(i), right.slice(j))Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputArray 5,1,4,2,8
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state