Dynamic Programming21 sections · 916 units
Open in Course

Challenge: Off-by-One Errors

Getting indices right

The formula prefix[r+1]prefix[l]prefix[r+1] - prefix[l] uses 1-indexed prefixes. If your array is 0-indexed, be careful. Common mistake: using prefix[r]prefix[l1]prefix[r] - prefix[l-1] when l=0l = 0.

This accesses prefix[1]prefix[-1]. Handle the edge case or use 1-indexed prefixes. Test your implementation: sum of arr[0..0]arr[0..0] should be arr[0]arr[0]. Sum of arr[0..n1]arr[0..n-1] should be total sum. If these fail, check your indices. I recommend 1-indexed prefixes with prefix[0]=0prefix[0] = 0. Then sum(l,r)=prefix[r+1]prefix[l]sum(l, r) = prefix[r+1] - prefix[l] works for all valid ranges.