Count of Smaller Numbers After Self
For every array position, count later elements whose values are smaller.
Open on LeetCode ↗Intuition
Scanning the suffix for every index is direct but quadratic. During merge sort, the left and right halves preserve original ordering: every item in the right half originally appeared after every item in the left half. When a right value moves ahead of a left value during merging, it is a smaller later element for that left value. Carry original indices so these crossing counts are added to the correct answers.
A per-index question about later elements often becomes a crossing-pair count. If relationships can be counted while two sorted halves merge, indexed merge sort gives O(n log n) time.
Approach
Attach each value to its original position
Build pairs (value, index) before sorting. Values may move during merge sort, but the index lets every accumulated count update the corresponding output slot.
Count right-half elements that cross during merge
While merging, choose the right pair when its value is strictly smaller and increment moved_right. Whenever a left pair is emitted, add moved_right because precisely those right-half elements have crossed ahead of it.
Merge equal values without counting them
Choose from the left when values are equal because the problem asks for strictly smaller values. Recursively count crossings inside both halves, then count crossings between them, covering every ordered pair exactly once.
Solution
Common pitfalls
Counting equal values as smaller
if right[j][0] <= left[i][0]:
if right[j][0] < left[i][0]:
The requested relation is strictly smaller, not smaller or equal.
Losing original positions
pairs = sorted(nums)
pairs = [(value, i) for i, value in enumerate(nums)]
Counts must be written back in input order after values move.
Adding all right elements
answer[left[i][1]] += len(right)
answer[left[i][1]] += moved_right
Only right elements already moved ahead are proven smaller than the current left value.
Edge cases
Equality selects the left element, so no false smaller counts are added.
Each left-side item accumulates all smaller items to its right across merge levels.
Comparisons use actual integer values and original indices, so both are handled naturally.