LeetCode 327 Count of Range Sum - Why Naive Fails

The trap

Checking all O(n2)O(n^2) subarrays and their sums takes O(n2)O(n^2). With prefix sums, sum computation is O(1)O(1), but still O(n2)O(n^2) pairs.

Example: n=105n = 10^5. Checking all 5×1095 \times 10^9 subarray pairs is too slow.

Prefix sums + merge sort: count pairs of prefix sums where lowerprefix[j]prefix[i]upperlower \le prefix[j] - prefix[i] \le upper. During merge, both halves are sorted. Two pointers count valid pairs. O(nlogn)O(n \log n).