You see a problem: "Find the longest subarray with sum equal to k." You think: "Subarray problem... should I use prefix sum or sliding window?"
This confusion costs interviews. Both patterns solve subarray problems, but they're designed for different scenarios. Use the wrong one, and your solution either fails or is unnecessarily complex.
In this guide, you'll learn when to use each pattern, the key differences, and a decision framework that works every time.
TL;DR
Use Prefix Sum when:
- Multiple range queries on static array
- Exact target sum (can be any value)
- Array has negative numbers
- Counting subarrays with condition
Use Sliding Window when:
- Finding longest/shortest subarray
- All positive numbers (or all non-negative)
- Variable window size with condition
- Maximum/minimum subarray value
Quick decision:
- Target sum + negatives → Prefix Sum + Hash Map
- Longest/shortest + positives → Sliding Window
- Multiple queries → Prefix Sum
- Single pass optimization → Sliding Window
The Core Difference
Prefix Sum: Range Queries
Purpose: Answer "what's the sum from index i to j?"
Approach: Precompute cumulative sums, query in O(1)
Best for:
- Multiple queries
- Exact target sum
- Static array
Example:
# Build once
prefix = [0, 1, 3, 6, 10, 15]
# Query many times in O(1)
sum(2, 4) = prefix[5] - prefix[2] = 15 - 3 = 12Sliding Window: Contiguous Subarrays
Purpose: Find "longest/shortest subarray meeting condition"
Approach: Expand/shrink window dynamically
Best for:
- Finding optimal subarray
- Variable window size
- Positive numbers only
Example:
# Find longest subarray with sum ≤ k
left = 0
for right in range(n):
window_sum += nums[right]
while window_sum > k:
window_sum -= nums[left]
left += 1
max_len = max(max_len, right - left + 1)Side-by-Side Comparison
| Aspect | Prefix Sum | Sliding Window |
|---|---|---|
| Purpose | Range queries | Find optimal subarray |
| Preprocessing | O(n) build | None |
| Query time | O(1) | O(n) |
| Space | O(n) | O(1) |
| Array type | Any (negatives OK) | Positive numbers |
| Use case | Multiple queries | Single optimization |
| Window size | Fixed range | Variable |
| Typical goal | Exact sum | Longest/shortest |
Decision Framework
Question 1: Fixed or Variable Size?
Fixed size (k elements):
→ Use Sliding Window (simpler)
Variable size (find optimal):
→ Continue to Question 2
Question 2: Multiple Queries or Single Pass?
Multiple queries:
→ Use Prefix Sum (preprocess once, query many)
Single pass:
→ Continue to Question 3
Question 3: Exact Target or Optimization?
Exact target sum:
→ Continue to Question 4
Longest/shortest/maximum:
→ Use Sliding Window
Question 4: Positive or Negative Numbers?
All positive (or non-negative):
→ Use Sliding Window
Has negative numbers:
→ Use Prefix Sum + Hash Map
Example 1: Maximum Subarray Sum (Fixed Size)
Problem
Find maximum sum of subarray of size k.
When to Use Sliding Window
Input: All numbers (positive or negative)
Goal: Maximum sum
Window: Fixed size k
Solution: Sliding Window
def maxSumFixedWindow(nums, k):
window_sum = sum(nums[:k])
max_sum = window_sum
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i-k]
max_sum = max(max_sum, window_sum)
return max_sumWhy: Fixed window size, single pass optimization.
When to Use Prefix Sum
If you need multiple queries:
# Answer: "What's max sum for window size 3? 5? 7?"
# Prefix sum allows O(1) per queryExample 2: Subarray Sum Equals K
Problem
Count subarrays with sum equal to k.
When Sliding Window Fails
Input: nums = [1, -1, 1, 1], k = 1
Sliding window approach (WRONG):
# This doesn't work because negatives break monotonicity
left = 0
count = 0
window_sum = 0
for right in range(len(nums)):
window_sum += nums[right]
while window_sum > k and left <= right:
window_sum -= nums[left]
left += 1
if window_sum == k:
count += 1
# Result: 1 (WRONG! Should be 4)
# Misses: [1,-1,1], [-1,1,1], [1]Why it fails: Negatives mean window_sum can increase or decrease, breaking the "shrink when too large" logic.
When Prefix Sum + Hash Map Works
Correct approach:
def subarraySum(nums, k):
count = 0
prefix_sum = 0
sum_count = {0: 1}
for num in nums:
prefix_sum += num
if prefix_sum - k in sum_count:
count += sum_count[prefix_sum - k]
sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
return count
# Result: 4 ✓Why it works: Hash map tracks all previous prefix sums, handles negatives correctly.
Example 3: Minimum Size Subarray Sum
Problem
Find minimum length subarray with sum ≥ target (all positive numbers).
When Sliding Window Works
Input: All positive numbers
Goal: Minimum length
Condition: Sum ≥ target
Solution: Sliding Window
def minSubArrayLen(target, nums):
left = 0
window_sum = 0
min_len = float('inf')
for right in range(len(nums)):
window_sum += nums[right]
while window_sum >= target:
min_len = min(min_len, right - left + 1)
window_sum -= nums[left]
left += 1
return min_len if min_len != float('inf') else 0Why: Positive numbers ensure monotonicity—adding elements increases sum, removing decreases it.
When Prefix Sum is Overkill
Prefix sum approach would work but is more complex:
# Requires binary search or two pointers on prefix array
# Sliding window is simpler and more intuitiveExample 4: Longest Substring Without Repeating Characters
Problem
Find longest substring with all unique characters.
Why Prefix Sum Doesn't Apply
This isn't a sum problem!
Solution: Sliding Window + Hash Set
def lengthOfLongestSubstring(s):
left = 0
seen = set()
max_len = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
max_len = max(max_len, right - left + 1)
return max_lenPattern: Sliding window works for any condition, not just sums.
Common Mistakes
Mistake 1: Using Sliding Window with Negatives
❌ Wrong:
# Array has negatives
nums = [1, -1, 5, -2, 3]
# Using sliding window for "sum equals k"
# Will miss valid subarrays!✅ Correct:
# Use prefix sum + hash mapMistake 2: Using Prefix Sum for "Longest"
❌ Wrong:
# Finding longest subarray with sum ≤ k (all positive)
# Using prefix sum + binary search
# Overcomplicated!✅ Correct:
# Use sliding window (simpler)Mistake 3: Confusing "Exact Sum" with "At Most"
Exact sum = k: Prefix sum + hash map
Sum ≤ k (positives): Sliding window
Sum ≥ k (positives): Sliding window
When to Use Prefix Sum
✅ Use Prefix Sum When:
- Multiple range queries on static array
- Exact target sum with any numbers
- Counting subarrays with sum condition
- Array has negative numbers
- Need O(1) query time after preprocessing
Example problems:
- Range Sum Query (#303)
- Subarray Sum Equals K (#560)
- Continuous Subarray Sum (#523)
When to Use Sliding Window
✅ Use Sliding Window When:
- Finding longest/shortest subarray
- All positive numbers (or non-negative)
- Variable window size with condition
- Maximum/minimum value in subarray
- Single pass optimization
Example problems:
- Minimum Size Subarray Sum (#209)
- Longest Substring Without Repeating Characters (#3)
- Max Consecutive Ones III (#1004)
Visual Decision Tree
Subarray/Substring Problem
|
v
Multiple queries?
/ \
YES NO
| |
v v
Prefix Sum What's the goal?
/ | \
Exact Longest Maximum
Sum /Shortest Value
| | |
v v v
Negatives? Positives? Sliding
/ \ | Window
YES NO v
| | Sliding
v v Window
Prefix Sliding
Sum Window
+Hash
MapPractice Problems
Prefix Sum Problems
- Range Sum Query - Immutable (#303)
- Subarray Sum Equals K (#560)
- Continuous Subarray Sum (#523)
- Subarray Sums Divisible by K (#974)
Sliding Window Problems
- Minimum Size Subarray Sum (#209)
- Longest Substring Without Repeating Characters (#3)
- Max Consecutive Ones III (#1004)
- Fruit Into Baskets (#904)
Could Use Either (Choose Wisely)
- Maximum Average Subarray I (#643) - Fixed size → Sliding Window
- Find All Anagrams in a String (#438) - Fixed size → Sliding Window
FAQ
Q: Can I use sliding window with negative numbers?
A: Only if you're finding longest/shortest with a monotonic condition (e.g., sum ≥ k). For exact sum with negatives, use prefix sum + hash map.
Q: Which is faster?
A: Sliding window is O(n) time, O(1) space. Prefix sum is O(n) time, O(n) space. Sliding window is more space-efficient when applicable.
Q: Can I combine both patterns?
A: Rarely needed. They solve different problem types. Choose one based on the problem requirements.
Q: What if I need multiple queries AND have negatives?
A: Use prefix sum. Build once, query many times with hash map lookups.
Q: How do I remember which to use?
A: Mnemonic: "Exact sum + negatives → Prefix. Longest + positives → Sliding."
Conclusion
Prefix sum and sliding window solve different types of subarray problems.
Key differences:
- Prefix sum: Range queries, exact sums, negatives OK
- Sliding window: Longest/shortest, positives only, variable size
Decision rules:
- Multiple queries → Prefix Sum
- Exact sum + negatives → Prefix Sum + Hash Map
- Longest/shortest + positives → Sliding Window
- Fixed window size → Sliding Window
The patterns:
Prefix Sum:
prefix_sum = 0
sum_count = {0: 1}
for num in nums:
prefix_sum += num
if prefix_sum - k in sum_count:
count += sum_count[prefix_sum - k]
sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1Sliding Window:
left = 0
for right in range(n):
# Expand window
window_sum += nums[right]
# Shrink if needed
while condition_violated:
window_sum -= nums[left]
left += 1
# Update result
max_len = max(max_len, right - left + 1)Master this distinction, and you'll choose the right pattern instantly. For more, see the complete prefix sum guide, sliding window guide, and when prefix sum fails.
Next time you see a subarray problem, ask: "Exact sum or longest? Negatives or positives?"
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
