#327

Count of Range Sum

Hard Fenwick tree over compressed prefix sums

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count subarrays whose sum lies within [lower, upper].

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count subarrays with sum in [lower, upper].

Why this works: with prefix sums, count earlier prefixes in [P - upper, P - lower] for each P. Compress the values and count with a Fenwick tree.

Example: [-2, 5, -1], range [-2, 2]

valid: [-2], [-1], [-2, 5, -1] → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using int prefix sums — they overflow with values near 2^31.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Segment Tree, Fenwick & Sparse Table
🎬 Episodes 98–100: video coming soon