LeetCode 315 Count of Smaller Numbers After Self - Solution

The core idea

Process from right, maintaining sorted structure. Count elements smaller than current.

It works because as you add elements from right to left, the sorted structure tells you how many existing elements are smaller.

Example: [5,2,6,1]. Process 11: 00 smaller. Process 66: 11 smaller. Process 22: 11 smaller. Process 55: 22 smaller. Result: [2,1,1,0].

Segment tree or merge sort. For n=105n = 10^5: O(nlogn)O(n \log n) time. Merge sort: 105×171.7×10610^5 \times 17 \approx 1.7 \times 10^6 operations. O(n)O(n) space.