Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Prefix Sum High frequency Solution Available Practice Mode

Subarray Sum Equals K LeetCode Solution

Tags: #Array #Hash Map #Prefix Sum

Approach Summary

Track prefix sums in a hash map. At each position, if (currentSum - k) exists in the map, that count is the valid subarrays ending here.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Prefix Sum Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Prefix Sum pattern.

Framework: Prefix Sum • Interview Prep: Tested at FAANG • Explore all Prefix Sum problems & invariants →

How to Recognize This Pattern

  • Count subarrays with exact sum
  • Prefix sum + hash map

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

Array Hash Map Prefix Sum

Frequently Asked Questions

What is the optimal time and space complexity for Subarray Sum Equals K?
The optimal solution for Subarray Sum Equals K achieves O(n) runtime complexity and requires O(n) auxiliary space. One pass with O(1) map operations per element — O(n) time. The map holds up to n distinct prefix sums — O(n) space.
How do I identify that Subarray Sum Equals K requires the Prefix Sum pattern?
In technical interviews, look for key problem signals: Count subarrays with exact sum; Prefix sum + hash map. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Prefix Sum strategy.
What critical edge cases must be handled in Subarray Sum Equals K?
Essential edge cases to verify include: Negative numbers — prefix sums are not monotonic, but the hash map handles any values; k = 0 — counts subarrays summing to zero, including empty-ish runs; A single element equal to k; The whole array summing to k — handled by the {0: 1} initialization. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Subarray Sum Equals K?
Subarray Sum Equals K is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Google, Amazon, Oracle, Stripe.
Buy me a coffee
Daily Practice
0/0