LeetCode Problem

How to Solve Subarray Sum Equals K

To solve Subarray Sum Equals K, iterate through nums while maintaining a prefix sum and a hash map of seen sums. For each position, check if currentSum - k exists in the map to count valid subarrays. This approach avoids nested loops and reduces time complexity, leveraging the array scanning plus hash lookup pattern efficiently.

GhostInterview Help

Need help with Subarray Sum Equals K without spending extra time grinding it?

GhostInterview can read Subarray Sum Equals K from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #560Array scanning plus hash lookupReviewed 2026-03-08
Difficulty
Medium
Primary pattern
Array scanning plus hash lookup
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

To solve Subarray Sum Equals K, iterate through nums while maintaining a prefix sum and a hash map of seen sums. For each position, check if currentSum - k exists in the map to count valid subarrays. This approach avoids nested loops and reduces time complexity, leveraging the array scanning plus hash lookup pattern efficiently.

Problem Statement

Given an integer array nums and an integer k, determine the total number of contiguous subarrays whose sum equals k. Each subarray must consist of consecutive elements in nums.

For example, with nums = [1,1,1] and k = 2, there are 2 subarrays that meet the criteria. Implement an efficient solution that handles large arrays without checking all possible subarrays explicitly.

Examples

Example 1

Input: nums = [1,1,1], k = 2

Output: 2

Example details omitted.

Example 2

Input: nums = [1,2,3], k = 3

Output: 2

Example details omitted.

Constraints

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -107 <= k <= 107

Solution Approach

Prefix Sum with Hash Map

Maintain a running prefix sum and use a hash map to store how many times each sum has occurred. For each element, increment the count by the number of times (currentSum - k) appears in the map. This exploits the array scanning plus hash lookup pattern and avoids nested iteration.

Iterative Single Pass

Scan through nums once, updating the current cumulative sum and consulting the hash map in each iteration. Add currentSum to the map after counting. This ensures O(n) time and captures all valid subarrays without recomputation.

Edge Case Handling

Initialize the hash map with {0:1} to account for subarrays starting at index 0. Carefully handle negative numbers and zeros, as they may influence the prefix sums and hash lookups, ensuring correctness across all integer ranges.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

Time complexity is O(n) since each element is processed once and hash map lookups are constant on average. Space complexity is O(n) due to storing prefix sums in the hash map.

What Interviewers Usually Probe

  • Checks if candidate considers brute-force inefficiency with nested loops.
  • Looks for use of prefix sum combined with hash lookup to count subarrays.
  • Observes whether edge cases like negative numbers and zero sums are handled correctly.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to initialize hash map with 0:1, causing missed subarrays starting at index 0.
  • Using nested loops which lead to O(n^2) performance and timeouts.
  • Neglecting negative numbers or zeros which can invalidate prefix sum assumptions.

Follow-up variants

  • Return all subarrays themselves instead of just the count using a similar prefix sum map.
  • Find the longest subarray with sum equal to k, adjusting the map to store earliest indices.
  • Count subarrays with sum less than or equal to k, modifying lookup logic to handle ranges.

How GhostInterview Helps

  • Highlights the array scanning plus hash lookup pattern for immediate implementation.
  • Detects common pitfalls like incorrect initialization or overlooked negatives and zeros.
  • Offers fast, step-by-step guidance to translate the problem into an efficient O(n) solution.

Topic Pages

FAQ

What is the most efficient approach for Subarray Sum Equals K?

Use a prefix sum combined with a hash map to count occurrences of currentSum - k, achieving O(n) time complexity.

Can negative numbers be handled in this problem?

Yes, the prefix sum plus hash map approach works with negative numbers because it tracks cumulative sums accurately.

Why not use a brute-force nested loop?

Nested loops lead to O(n^2) time and will fail on large arrays; prefix sum with hash lookup is necessary for efficiency.

How do I account for subarrays starting at index 0?

Initialize the hash map with {0:1} to count subarrays that sum to k from the beginning of the array.

What pattern does this problem exemplify?

It exemplifies the array scanning plus hash lookup pattern where cumulative sums are mapped to frequencies for quick subarray counting.

GhostInterview Solver

Need direct help with Subarray Sum Equals K instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Subarray Sum Equals K from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.