- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 74 lines of Python from the credited upstream file 327.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def countRangeSum(self, nums: list[int], lower: int, upper: int) -> int:3 n = len(nums)4 self.ans = 05 prefix = list(itertools.accumulate(nums, initial=0))6 7 self._mergeSort(prefix, 0, n, lower, upper)8 return self.ans9 10 def _mergeSort(11 self,12 prefix: list[int],13 l: int,14 r: int,15 lower: int,16 upper: int,17 ) -> None:18 if l >= r:19 return20 21 m = (l + r) 222 self._mergeSort(prefix, l, m, lower, upper)23 self._mergeSort(prefix, m + 1, r, lower, upper)24 self._merge(prefix, l, m, r, lower, upper)25 26 def _merge(27 self,28 prefix: list[int],29 l: int,30 m: int,31 r: int,32 lower: int,33 upper: int,34 ) -> None:35 lo = m + 1 36 hi = m + 1 37 38 39 for i in range(l, m + 1):40 while lo <= r and prefix[lo] - prefix[i] < lower:41 lo += 142 while hi <= r and prefix[hi] - prefix[i] <= upper:43 hi += 144 self.ans += hi - lo45 46 sorted = [0] * (r - l + 1)47 k = 0 48 i = l 49 j = m + 1 50 51 while i <= m and j <= r:52 if prefix[i] < prefix[j]:53 sorted[k] = prefix[i]54 k += 155 i += 156 else:57 sorted[k] = prefix[j]58 k += 159 j += 160 61 62 while i <= m:63 sorted[k] = prefix[i]64 k += 165 i += 166 67 68 while j <= r:69 sorted[k] = prefix[j]70 k += 171 j += 172 73 prefix[l:l + len(sorted)] = sorted74