LeetCode 315 Count of Smaller Numbers After Self - Why Naive Fails

The trap

For each element, scanning all elements to its right takes O(n)O(n). Total: O(n2)O(n^2). For n=105n = 10^5, that's 101010^{10} operations.

Example: nums = [5, 2, 6, 1]. For 55: count [2,1][2, 1] smaller = 22. For 22: count [1][1] smaller = 11. Scanning rightward for each element is slow.

Merge sort while counting inversions, or segment tree for range queries. Process right to left, query count of elements smaller than current, then add current to structure. O(nlogn)O(n \log n).