Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Prefix Sum

Subarray Sum Equals K

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Write a function that returns the total number of contiguous subarrays within a given integer array whose elements sum up to a target K.

Example 1: Input:

nums = [3, 4, 7, 2, -3, 1, 4, 2]
k = 7

Output: 4

Explanation: The subarrays that sum to 7 are:

[3, 4], [7], [7, 2, -3, 1], [1, 4, 2]

Example 2: Input:

nums = [1, -1, 0]
k = 0

Output: 3

Explanation: The subarrays that sum to 0 are:

[-1, 1], [0], [1, -1, 0]

Explanation

We can solve this question efficiently by leveraging the Prefix-Sum technique.
Let's start by visualizing the role that the prefix sum plays in this solving this problem. Let's say I have the following array:
32-12-31012345
I also have the sum of all the elements starting from the beginning of the array up to index 3 (arr[0] + arr[1] + arr[2] + arr[3]) stored in a variable sum_.
sum_632-12-31012345
I also have the prefix sums of all the elements up to index 2 stored in an array called prefix:
sum_632-12-310123450354​arr[0] + arr[1] + arr[2]0123prefixnums
When looking at these visuals, recall that prefix[i] contains the prefix sum of all elements up to i - 1 in the array.
prefix[i] = arr[0] + arr[1] + ... + arr[i - 1]
Each of the values in the prefix_sum array tells us about the sum of all the different subarrays that end at index 3:
For example, let's look at prefix[1], which is 3, but we'll refer to as x for now. From this, we can tell that there exists a subarray ending at index 3 that has a sum of sum_ - x (6 - 3 = 3):
sum - xxx32-12-3101234503540123prefixnumssum - x3
This applies to each value in prefix:
sum - xx32-12-3101234503540123prefixnumssum - x6 sum - xx5x32-12-3101234503540123prefixnumssum - x1 sum - xsum - xx32-12-3101234503540123prefixnumsx4
To recap, if we have:
  • a value sum_ that contains the prefix sum of the array up to index i
  • another value x that is the prefix sum of the array up to index j (where j comes before i)
then there exists a subarray ending at i with sum sum_ - x.
We'll use this fact to solve our problem.

Counting Subarrays with Sum K

The question is asking for the number of distinct subarrays that sum to k. So we can turn our prefix array into a dictionary mapping each prefix sum to the number of times it has been seen.
{ -2:1, 0:1, 1:1, 2:2, 4:1, 7: 1 }2-1-3423012345prefix_countsnumsprefix021-2274
The prefix_counts dictionary maps each value in prefix to the number of times it appears in the array.
Now, we can use this dictionary to count the number of subarrays that sum to k that end at each index in the array.
Recall from above, we can calculate the sum of any subarray ending at index j by using the difference of prefix sums: if the current prefix sum up to index j is sum_, and there was an earlier prefix sum prev_sum at some index before j, then the subarray sum between them is sum_ - prev_sum.
This means that to find a subarray that sums to k ending at the current index (with prefix sum sum_), we need to find a previous prefix sum equal to sum_ - k in the prefix_counts dictionary. More importantly, the number of subarrays that sum to k that end at index i is equal to prefix_counts[sum_ - k].
Here's a visual to help us understand this better:
For example, let's say we have the array below and we are interested in finding the number of subarrays that sum to k = 5. At index 5, we have sum_ = 7
{ -2:1, 0:1, 1:1, 2:2, 4:1, 7: 1 }2-1-3423012345prefix_countsnumssum7
Since we are looking for subarrays that sum to k = 5 and end at index 5, this is equivalent to finding a prefix sum sum_ such that sum_ - k = 7 - 5 = 2. The prefix_counts dictionary tells us that there are 2 of these prefix sums, so there are 2 subarrays that sum to k = 5 and end at index 5:
{ -2:1, 0:1, 1:1, 2:2, 4:1, 7: 1 }2-1-3423012345prefix_countsnumssum7
The two subarrays that sum to 5 and end at index 5 are underlined in green.

Solution

At a high level, our solution will iterate over each element in the array and calculate the number of subarrays that sum to k that end at that index using the approach outlined above. We will keep track of the total number of subarrays that sum to k as we iterate over the array, and return it at the end.
  • initialize a prefix_counts dictionary with a single entry 0: 1. The entry 0: 1 represents that an empty subarray sums to 0, which lets us correctly account for subarrays that start at index 0 and sum to k. The values in the dictionary represent the number of times we have seen a particular prefix sum as we iterate.
  • initialize sum_ to 0 and count to 0. sum_ represents the prefix sum up to the current index, and count represents the total number of subarrays that sum to k.
  • iterate over the array, updating sum_ and count as follows:
    • update sum_ by adding the current element to it.
    • calculate the number of subarrays that sum to k that end at the current index by looking up prefix_counts[sum_ - k] and adding it to count.
    • update the prefix_counts dictionary by incrementing the count of sum_ by 1.
Solution
Python
Language
class Solution:
def subarraySum(self, nums, k):
count = 0
sum_ = 0
prefix_counts = {0: 1}
for num in nums:
sum_ += num
if sum_ - k in prefix_counts:
count += prefix_counts[sum_ - k]
# update the seen prefix sum counts
prefix_counts[sum_] = prefix_counts.get(sum_, 0) + 1
return count
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(N) where N is the length of the input array nums. We iterate over the array once, and for each element, we perform constant time operations.

Space Complexity: O(N) where N is the length of the input array nums. We use a dictionary prefix_counts to store the number of times we have seen each prefix sum, which can have at most N entries.

Mark as read

Next: Spiral Matrix

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Counting Subarrays with Sum K

Solution

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress