Technique
Divide and Conquer (merge-sort counting)
Split the array in half, solve each half, then count/merge cross pairs in linear time while merging sorted halves.
0%
mastery
0/10 solved
0/10 solved
Recognise it
The signal
count inversions / pairs i<j with a condition on values
1Brute force
Check all pairs O(n2).
2The observation
Cross pairs: when both halves are sorted, cross pairs are counted with two pointers.
3Why it works
Each pair (i, j) is counted exactly at the level where i and j are first split apart.
Reach for it when
- +sort a linked list
- +closest pair of points
Not when
- ×online updates (use BIT)
- ×condition not monotone on sorted halves
Practice
0/10 solved
- Masha and a Beautiful TreeCodeforces1300
- Permutation TransformationCodeforces1200
- Sort an ArrayAmazon, MicrosoftMedium
- Sort ListAmazon, AdobeMedium
- a-Good StringCodeforces1500
- Minimum Euclidean DistanceCSESHard
- Count of Smaller Numbers After SelfGoogle, CitadelHard
- Reverse PairsGoogle, CitadelHard
- Count of Range SumHard
- Merge k Sorted ListsAmazon, MetaHard
Pitfalls
Misconceptions
- !counting during merge with the wrong pointer (reverse-pairs needs a separate counting pass)
Looks like it, isn't
- Global and Local Inversions needs Invariants & Parity Arguments
Why
For a permutation of 0..n-1, global == local iff |nums[i] - i| <= 1 for all i. Counting inversions is unnecessary. source ↗
Go deepervariants and techniques · 1 combinations · resources
Combinations
CDQ Divide and Conquer+Segment Tree / Fenwick (BIT)
2D point updates/queries (or swaps in permutations) all offline, n ~ 2e5
- CDQ Divide and Conquer:
- split operations by time; left updates feed right queries
- Segment Tree / Fenwick (BIT):
- a BIT over one coordinate during the merge sweep