LeetCopilot Logo
LeetCopilot
LeetCode Pattern/Hash Map/Why Your Subarray Sum Equals K Solution Fails (3 Common Bugs)

Why Your Subarray Sum Equals K Solution Fails (3 Common Bugs)

LeetCopilot Team
Dec 22, 2025
7 min read
Hash MapPrefix SumDebuggingCommon Mistakes
Getting 'Wrong Answer' on Subarray Sum Equals K? Learn the 3 bugs that trip up 90% of developers and how to fix them instantly.

You're solving "Subarray Sum Equals K." You write what looks like a perfect prefix sum + hash map solution.

You submit. Wrong Answer.

Test case 23 fails. You can't figure out why.

This is frustrating because the pattern seems straightforward. But there are 3 specific bugs that trip up 90% of developers on this problem.

This guide shows you exactly what they are and how to fix them.

Bug 1: Forgetting {0: 1} Initialization

The Problem

This is the #1 most common mistake on Subarray Sum Equals K.

Wrong (missing initialization):

python
def subarraySum(nums, k):
    count = 0
    prefix_sum = 0
    sum_count = {}  # Missing {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

Why It Fails

Test case: nums = [1, 2, 3], k = 3

Expected: 2 (subarrays [1, 2] and [3])

Trace without {0: 1}:

text
i=0: prefix=1, check 1-3=-2 (not found), add {1: 1}, count=0
i=1: prefix=3, check 3-3=0 (not found!), add {1: 1, 3: 1}, count=0
i=2: prefix=6, check 6-3=3 (found!), count=1, add {1: 1, 3: 1, 6: 1}

Result: 1 ❌ (should be 2)

What we missed: Subarray [1, 2] (sum = 3)

The Fix

Correct (with initialization):

python
def subarraySum(nums, k):
    count = 0
    prefix_sum = 0
    sum_count = {0: 1}  # Critical!
    
    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

Trace with {0: 1}:

text
i=0: prefix=1, check 1-3=-2 (not found), add {0: 1, 1: 1}, count=0
i=1: prefix=3, check 3-3=0 (found!), count=1, add {0: 1, 1: 1, 3: 1}
i=2: prefix=6, check 6-3=3 (found!), count=2, add {0: 1, 1: 1, 3: 1, 6: 1}

Result: 2 ✓

Why {0: 1} Is Needed

Conceptual meaning: "There's one way to get sum 0: take nothing (empty prefix)."

Practical effect: Handles subarrays that start from index 0.

When prefix_sum = k, we need prefix_sum - k = 0 to exist in the map.

The rule: For any prefix sum + hash map problem, initialize with {0: 1}.

Bug 2: Wrong Order of Operations

The Problem

Updating the map before checking causes double-counting.

Wrong (update before check):

python
def subarraySum(nums, k):
    count = 0
    prefix_sum = 0
    sum_count = {0: 1}
    
    for num in nums:
        prefix_sum += num
        
        # Wrong order!
        sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
        if prefix_sum - k in sum_count:
            count += sum_count[prefix_sum - k]
    
    return count

Why It Fails

Test case: nums = [1], k = 0

Expected: 0 (no subarray sums to 0)

Trace with wrong order:

text
i=0: prefix=1
     Add {0: 1, 1: 1}
     Check 1-0=1 (found!), count=1

Result: 1 ❌ (should be 0)

What went wrong: We added prefix_sum = 1 to the map, then immediately found it when checking for prefix_sum - k = 1. This counts the current element as a subarray by itself, which is wrong when k = 0.

The Fix

Correct (check before update):

python
def subarraySum(nums, k):
    count = 0
    prefix_sum = 0
    sum_count = {0: 1}
    
    for num in nums:
        prefix_sum += num
        
        # Correct order: check FIRST
        if prefix_sum - k in sum_count:
            count += sum_count[prefix_sum - k]
        
        # Then update
        sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
    
    return count

Trace with correct order:

text
i=0: prefix=1
     Check 1-0=1 (not found), count=0
     Add {0: 1, 1: 1}

Result: 0 ✓

The rule: Always check before updating the map.

Bug 3: Misunderstanding Negative Numbers

The Problem

Thinking you can use sliding window because "it's a subarray problem."

Wrong (trying sliding window):

python
def subarraySum(nums, k):
    # Trying to use sliding window
    left = 0
    current_sum = 0
    count = 0
    
    for right in range(len(nums)):
        current_sum += nums[right]
        
        while current_sum > k:  # When to shrink?
            current_sum -= nums[left]
            left += 1
        
        if current_sum == k:
            count += 1
    
    return count

Why It Fails

Test case: nums = [1, -1, 1, 1], k = 2

Expected: 3 (subarrays [1, -1, 1, 1], [1, 1], [1, 1])

Why sliding window fails: With negative numbers, shrinking doesn't guarantee the sum decreases. You lose the monotonicity property that sliding window requires.

Example:

text
At right=2: sum=1, should we shrink?
If we shrink, we might miss valid subarrays!

The Fix

Correct (use prefix sum + hash map):

python
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

The rule: If array has negative numbers or you need exact sum, use prefix sum + hash map, not sliding window.

The Correct Template

Here's the bug-free template:

python
def subarraySum(nums: List[int], k: int) -> int:
    """
    Count subarrays with sum equals k.
    
    Time: O(n)
    Space: O(n)
    """
    count = 0
    prefix_sum = 0
    sum_count = {0: 1}  # Bug 1: Must initialize!
    
    for num in nums:
        prefix_sum += num
        
        # Bug 2: Check BEFORE updating
        if prefix_sum - k in sum_count:
            count += sum_count[prefix_sum - k]
        
        # Update after checking
        sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
    
    return count

Debugging Checklist

If your solution fails, check:

1. Initialization

  • Did you initialize with {0: 1}?
  • Not {} or {0: 0}?

2. Order of Operations

  • Are you checking before updating?
  • Not updating then checking?

3. Pattern Choice

  • Are you using prefix sum + hash map?
  • Not trying sliding window with negative numbers?

4. Formula

  • Are you checking prefix_sum - k?
  • Not k - prefix_sum?

5. Update Logic

  • Are you incrementing count: sum_count.get(prefix_sum, 0) + 1?
  • Not setting to 1?

Common Test Cases

Test your solution with these:

python
# Test 1: Basic
nums = [1, 2, 3], k = 3
# Expected: 2 ([1,2] and [3])

# Test 2: From start
nums = [1, 1, 1], k = 2
# Expected: 2 ([1,1] at indices 0-1 and 1-2)

# Test 3: Negative numbers
nums = [1, -1, 1, 1], k = 2
# Expected: 3

# Test 4: k = 0
nums = [1], k = 0
# Expected: 0

# Test 5: All zeros
nums = [0, 0, 0], k = 0
# Expected: 6 (all subarrays)

# Test 6: Single element equals k
nums = [3], k = 3
# Expected: 1

Quick Fixes

Fix 1: Missing {0: 1}

python
# Before
sum_count = {}

# After
sum_count = {0: 1}

Fix 2: Wrong order

python
# Before
sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
if prefix_sum - k in sum_count:
    count += sum_count[prefix_sum - k]

# After
if prefix_sum - k in sum_count:
    count += sum_count[prefix_sum - k]
sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1

Fix 3: Using sliding window

python
# Before
# Sliding window code...

# After
# Use prefix sum + hash map template

Summary

The 3 bugs that cause "Wrong Answer" on Subarray Sum Equals K:

  1. Missing {0: 1} → Misses subarrays from start
  2. Wrong order → Double-counts or misses subarrays
  3. Using sliding window → Fails with negative numbers

The correct template:

python
count = 0
prefix_sum = 0
sum_count = {0: 1}  # Critical!

for num in nums:
    prefix_sum += num
    if prefix_sum - k in sum_count:  # Check first
        count += sum_count[prefix_sum - k]
    sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1  # Update after

return count

The debugging process:

  1. Check initialization: {0: 1}?
  2. Check order: Check before update?
  3. Check pattern: Prefix sum, not sliding window?

Next steps:

Fix these 3 bugs, and Subarray Sum Equals K becomes solvable.

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

Related Tutorials