You've implemented the difference array solution for Range Addition. The logic makes sense. You submit.
Wrong Answer.
The output is completely wrong—just an array of differences instead of the final values. Or maybe the last element is missing. Or the range boundaries are off by one.
Sound familiar? Difference array bugs are subtle because the technique has two distinct phases: applying updates and reconstructing. Miss one step or get the indices wrong, and the entire solution breaks.
In this guide, you'll learn the 4 most common difference array bugs, why they happen, and how to fix them permanently.
TL;DR
Common bugs:
- Forgetting final prefix sum → Returns difference array instead of result
- Off-by-one in range end → Doesn't update last element of range
- Wrong array size → Index out of bounds on
diff[end+1] - Updating in wrong order → Applying prefix sum too early
Correct template:
# 1. Initialize with size n+1
diff = [0] * (n + 1)
# 2. Apply ALL updates
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val # Note: end+1
# 3. Reconstruct with prefix sum
result = []
current = 0
for i in range(n):
current += diff[i]
result.append(current)
return result # Not diff!Common Bug 1: Forgetting the Final Prefix Sum
The Bug
# BUGGY CODE
def getModifiedArray(length, updates):
diff = [0] * (length + 1)
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val
return diff[:length] # BUG: Returning difference array!Example That Fails
length = 5
updates = [[1, 3, 2], [2, 4, 3]]
Expected: [0, 2, 5, 5, 3]
Got: [0, 2, 3, 0, -5, 0] # This is the difference array!Why It Happens
The difference array stores changes, not final values. You must apply prefix sum to reconstruct the actual array.
Trace:
After updates:
diff = [0, 2, 3, 0, -5, 0]
This means:
- At index 1: increase by 2
- At index 2: increase by 3 more
- At index 4: decrease by 5
To get final values, apply prefix sum:
result[0] = 0
result[1] = 0 + 2 = 2
result[2] = 2 + 3 = 5
result[3] = 5 + 0 = 5
result[4] = 5 + (-5) = 0
Wait, that gives [0, 2, 5, 5, 0], not [0, 2, 5, 5, 3]
Let me recalculate the updates:
Update [1,3,2]: diff[1]+=2, diff[4]-=2
diff = [0, 2, 0, 0, -2, 0]
Update [2,4,3]: diff[2]+=3, diff[5]-=3
diff = [0, 2, 3, 0, -2, -3]
Apply prefix sum:
result[0] = 0
result[1] = 0 + 2 = 2
result[2] = 2 + 3 = 5
result[3] = 5 + 0 = 5
result[4] = 5 + (-2) = 3
Result: [0, 2, 5, 5, 3] ✓The Fix
# FIXED CODE
def getModifiedArray(length, updates):
diff = [0] * (length + 1)
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val
# ✓ Apply prefix sum to reconstruct
result = []
current = 0
for i in range(length):
current += diff[i]
result.append(current)
return result # Return reconstructed arrayHow to Remember
Mnemonic: "Difference array stores changes. Prefix sum converts changes to values."
Always ask yourself: "Did I apply prefix sum at the end?"
Common Bug 2: Off-by-One in Range End
The Bug
# BUGGY CODE
for start, end, val in updates:
diff[start] += val
diff[end] -= val # BUG: Should be end+1Example That Fails
length = 5
updates = [[1, 3, 2]]
With bug (diff[end]):
diff = [0, 2, 0, -2, 0, 0]
After prefix sum: [0, 2, 2, 0, 0]
Expected: [0, 2, 2, 2, 0] # Should include index 3!Why It Happens
The plateau effect: We want to add val from start to end inclusive.
diff[start] += valstarts the plateaudiff[end+1] -= valends the plateau after indexend
If we use diff[end] -= val, the plateau ends at index end, not after it.
Visual:
Want to add 2 to range [1, 3]:
Correct (end+1):
diff = [0, 2, 0, 0, -2, 0]
[0, 2, 2, 2, 0, 0] ← Plateau from 1 to 3 ✓
Wrong (end):
diff = [0, 2, 0, -2, 0, 0]
[0, 2, 2, 0, 0, 0] ← Plateau from 1 to 2 only ❌The Fix
# FIXED CODE
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val # ✓ Correct: end+1How to Remember
Think: "I want the value to stop increasing after index end, so I decrement at end+1."
Common Bug 3: Not Initializing Array Size
The Bug
# BUGGY CODE
diff = [0] * length # BUG: Too small!
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val # Index out of bounds when end = length-1!Example That Fails
length = 5
updates = [[0, 4, 1]] # Update entire array
diff = [0] * 5 # Size 5
diff[0] += 1 # OK
diff[5] -= 1 # IndexError: list index out of range!Why It Happens
When end = length - 1, we need to access diff[end+1] = diff[length]. If the array only has size length, this is out of bounds.
The Fix
# FIXED CODE
diff = [0] * (length + 1) # ✓ Extra space for end+1
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val # Safe even when end = length-1How to Remember
Rule: Always initialize difference array with size n + 1.
Common Bug 4: Updating in Wrong Order
The Bug
# BUGGY CODE
result = [0] * length
current = 0
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val
# BUG: Applying prefix sum after each update
for i in range(length):
current += diff[i]
result[i] = currentWhy It's Wrong
This applies prefix sum k times (once per update) instead of once at the end. It's inefficient and gives wrong results because you're accumulating the difference array multiple times.
The Fix
# FIXED CODE
diff = [0] * (length + 1)
# Apply ALL updates first
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val
# Then reconstruct ONCE
result = []
current = 0
for i in range(length):
current += diff[i]
result.append(current)How to Remember
Two-phase approach:
- Phase 1: Apply all updates to difference array
- Phase 2: Reconstruct final array with prefix sum
Never mix the phases!
Step-by-Step Debugging Process
Step 1: Check Array Size
# Should be length + 1
assert len(diff) == length + 1Step 2: Verify Update Logic
# Print difference array after updates
print("Difference array:", diff)
# Should see:
# - Positive values at start indices
# - Negative values at end+1 indicesStep 3: Check Prefix Sum Application
# Trace prefix sum manually
current = 0
for i in range(length):
current += diff[i]
print(f"i={i}, diff[i]={diff[i]}, current={current}")Step 4: Test Edge Cases
# Edge case 1: Update entire array
updates = [[0, length-1, 1]]
# Edge case 2: Update single element
updates = [[0, 0, 1]]
# Edge case 3: Overlapping updates
updates = [[0, 2, 1], [1, 3, 2]]
# Edge case 4: Negative values
updates = [[0, 2, -1]]The Correct Template
Python
def range_addition(length: int, updates: List[List[int]]) -> List[int]:
"""
Apply multiple range updates efficiently.
Time: O(n + k), Space: O(n)
"""
# Step 1: Initialize difference array (size n+1)
diff = [0] * (length + 1)
# Step 2: Apply all updates
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val
# Step 3: Reconstruct with prefix sum
result = []
current = 0
for i in range(length):
current += diff[i]
result.append(current)
return resultJavaScript
function rangeAddition(length, updates) {
// Step 1: Initialize
const diff = new Array(length + 1).fill(0);
// Step 2: Apply updates
for (const [start, end, val] of updates) {
diff[start] += val;
diff[end + 1] -= val;
}
// Step 3: Reconstruct
const result = [];
let current = 0;
for (let i = 0; i < length; i++) {
current += diff[i];
result.push(current);
}
return result;
}Java
public int[] rangeAddition(int length, int[][] updates) {
// Step 1: Initialize
int[] diff = new int[length + 1];
// Step 2: Apply updates
for (int[] update : updates) {
int start = update[0], end = update[1], val = update[2];
diff[start] += val;
diff[end + 1] -= val;
}
// Step 3: Reconstruct
int[] result = new int[length];
int current = 0;
for (int i = 0; i < length; i++) {
current += diff[i];
result[i] = current;
}
return result;
}Real Debugging Example
The Student's Code
def getModifiedArray(length, updates):
diff = [0] * length # BUG 1: Size should be length+1
for start, end, val in updates:
diff[start] += val
diff[end] -= val # BUG 2: Should be end+1
return diff # BUG 3: Should apply prefix sumTest Case
length = 5
updates = [[1, 3, 2], [2, 4, 3]]
expected = [0, 2, 5, 5, 3]Debugging Process
Step 1: Run the code
result = getModifiedArray(5, updates)
print(result) # [0, 2, 3, -2, -3]
# Wrong! Expected [0, 2, 5, 5, 3]Step 2: Identify bugs
- Size is 5, should be 6 (might cause index error)
- Using
diff[end]instead ofdiff[end+1] - Returning
diffinstead of applying prefix sum
Step 3: Fix bugs
def getModifiedArray(length, updates):
diff = [0] * (length + 1) # ✓ Fix 1
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val # ✓ Fix 2
# ✓ Fix 3: Apply prefix sum
result = []
current = 0
for i in range(length):
current += diff[i]
result.append(current)
return resultStep 4: Verify
result = getModifiedArray(5, updates)
print(result) # [0, 2, 5, 5, 3] ✓Debugging Checklist
When your difference array solution fails:
-
Array size: Is it
length + 1? -
Range end: Using
end + 1, notend? -
Prefix sum: Applied at the end?
-
Return value: Returning result, not diff?
-
Update order: All updates before reconstruction?
-
Edge cases: Tested with full array update?
Practice Problems
Debug your skills with these problems:
- Range Addition (#370) - Basic template
- Corporate Flight Bookings (#1109) - 1-indexed variant
- Car Pooling (#1094) - Capacity checking
- Brightest Position on Street (#2021) - Event-based
FAQ
Q: Why do I need size n+1?
A: To safely access diff[end+1] when end = length-1.
Q: What if I forget to apply prefix sum?
A: You'll return the difference array (changes) instead of the final values. The output will be completely wrong.
Q: Can I apply prefix sum in-place?
A: Yes:
for i in range(1, length):
diff[i] += diff[i-1]
return diff[:length]Q: What if updates are 1-indexed?
A: Convert to 0-indexed:
diff[start - 1] += val
diff[end] -= val # end is already +1 after conversionQ: How do I know if my difference array is correct before applying prefix sum?
A: Check:
- Positive values at start indices
- Negative values at end+1 indices
- Sum of all values = sum of all update values
Conclusion
Difference array bugs are subtle but avoidable with the right checklist.
Key mistakes:
- Forgetting final prefix sum
- Using
endinstead ofend+1 - Array size
ninstead ofn+1 - Applying prefix sum too early
The correct process:
- Initialize
diff = [0] * (n + 1) - Apply all updates:
diff[start] += val; diff[end+1] -= val - Reconstruct with prefix sum
- Return result, not diff
The template:
diff = [0] * (length + 1)
for start, end, val in updates:
diff[start] += val
diff[end + 1] -= val
result = []
current = 0
for i in range(length):
current += diff[i]
result.append(current)
return resultMaster this checklist, and you'll never fail a difference array problem again. For more, see Difference Array, Off-by-One Errors, and the complete guide.
Next time you implement difference arrays, remember: size n+1, end+1, prefix sum at the end.
Want to Practice LeetCode Smarter?
LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.
Also compatible with Edge, Brave, and Opera
