Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

560. Subarray Sum Equals K

Medium44.4% Acceptance
ArrayHash TablePrefix Sum
Asked by:
F
Facebook
ProblemHints (4)Solutions (12)VideosCompanies (16)Notes

Problem Statement

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

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

Example 2:

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

Constraints:

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

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
A
Amazon
G
Google
M
Microsoft
O
Oracle
+11

Approach

The key challenge in #560 Subarray Sum Equals K is efficiently counting how many contiguous subarrays sum to a given value k. A naive approach checks every possible subarray using nested loops and calculates the sum each time, leading to O(n²) time complexity.

A more optimal method uses the concept of prefix sums. As you traverse the array, maintain a running cumulative sum. If the difference between the current prefix sum and k has appeared before, it means a subarray ending at the current index sums to k. To track this efficiently, store prefix sum frequencies in a hash map.

This approach allows you to update counts in constant time while scanning the array once. The prefix sum technique combined with hashing reduces the overall complexity to O(n) time with O(n) extra space, making it suitable for large inputs commonly seen in coding interviews.

Complexity

ApproachTime ComplexitySpace Complexity
Brute Force (Check all subarrays)O(n²)O(1)
Prefix Sum + Hash MapO(n)O(n)

Video Solution Available

take U forward

View all video solutions

Problem Hints

Use these hints if you're stuck. Try solving on your own first.

1
Hint 1

Will Brute force work here? Try to optimize it.

2
Hint 2

Can we optimize it by using some extra space?

3
Hint 3

What about storing sum frequencies in a hash table? Will it be useful?

4
Hint 4

sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.

Ready to see the solutions?View Solutions

Solutions (12)

Approach 1: Brute Force

This straightforward approach involves checking all possible subarrays in the given array. We calculate the sum for each subarray and check if it equals k. Although simple, it can be inefficient for large arrays due to its O(n^2) time complexity.

Time Complexity: O(n^2)
Space Complexity: O(1)

CC++JavaPythonC#JavaScript
1#include <stdio.h>
2
3int subarraySum(int* nums, int numsSize, int k) {
4    int count = 0;
5    for (int start = 0; start < numsSize; start++) {
6        int sum = 0;
7        for (int end = start; end < numsSize; end++) {
8            sum += nums[end];
9            if (sum == k) count++;
10        }
11    }
12    return count;
13}
14
15int main() {
16    int nums[] = {1, 1, 1};
17    int k = 2;
18    int size = sizeof(nums)/sizeof(nums[0]);
19    printf("%d\n", subarraySum(nums, size, k));
20    return 0;
21}
22

Explanation

This C code implements a nested loop where the outer loop selects the start of the subarray and the inner loop expands it, calculating the sum. If the sum equals k, it increments the count. The time complexity is O(n^2), and the space complexity is O(1).

Approach 2: Using HashMap for Prefix Sums

This optimized approach uses a hashmap to store prefix sums, facilitating the identification of subarrays with the desired sum in constant time. By keeping a count of prefix sums that have been seen, we can determine how many times a specific sum - k has appeared, suggesting that a subarray ending at the current position sums to k.

Time Complexity: O(n)
Space Complexity: O(n)

CC++JavaPythonC#JavaScript
1#



Video Solutions

Watch expert explanations and walkthroughs

Count Subarray sum Equals K | Brute - Better -Optimal

take U forward
24:09446,112 views

Asked By Companies

16 companies
F
Facebook
A
Amazon
G
Google
M
Microsoft
O
Oracle
T
TikTok
B
Bloomberg
V
Visa
A
Apple
Q
Quora
A
Adobe
E
Expedia
N
Nvidia
S
ServiceNow
D
DoorDash
B
Bolt

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Two SumEasy
Valid SudokuMedium
Sudoku SolverHard
First Missing PositiveHard
More similar problems

Related Topics

ArrayHash TablePrefix Sum

Problem Stats

Acceptance Rate44.4%
DifficultyMedium
Companies16

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Why are prefix sums used in Subarray Sum Equals K?

Prefix sums allow you to compute the sum of any subarray using the difference of two cumulative sums. When combined with a hash map to track previously seen sums, it helps detect valid subarrays quickly without recomputing sums repeatedly.

Is Subarray Sum Equals K asked in FAANG interviews?

Yes, this problem is commonly asked in FAANG and other top tech company interviews. It tests understanding of prefix sums, hash maps, and efficient counting of subarrays.

What is the optimal approach for Subarray Sum Equals K?

The optimal approach uses a prefix sum combined with a hash map. While traversing the array, you store frequencies of prefix sums and check if the difference between the current sum and k has appeared before. This allows counting valid subarrays in O(n) time.

What data structure is best for solving Subarray Sum Equals K?

A hash map (or dictionary) is the most useful data structure for this problem. It stores the frequency of prefix sums so you can quickly determine whether a previous prefix sum can form a subarray with sum k.

include
<stdio.h>
2
#
include
<stdlib.h>
3
#
include
<string.h>
4
5
int
subarraySum
(
int
*
nums
,
int
numsSize
,
int
k
)
{
6
int
count
=
0
,
sum
=
0
,
i
;
7
int
*
prefixSumCount
=
calloc
(
20000
,
sizeof
(
int
)
)
;
8
int
offset
=
10000
;
9
prefixSumCount
[
offset
]
=
1
;
10
11
for
(
i
=
0
;
i
<
numsSize
;
i
++
)
{
12
sum
+=
nums
[
i
]
;
13
int
target
=
sum
-
k
;
14
count
+=
prefixSumCount
[
target
+
offset
]
;
15
prefixSumCount
[
sum
+
offset
]
++
;
16
}
17
18
free
(
prefixSumCount
)
;
19
return
count
;
20
}
21
22
int
main
(
)
{
23
int
nums
[
]
=
{
1
,
1
,
1
}
;
24
int
k
=
2
;
25
int
size
=
sizeof
(
nums
)
/
sizeof
(
nums
[
0
]
)
;
26
printf
(
"%d\n"
,
subarraySum
(
nums
,
size
,
k
)
)
;
27
return
0
;
28
}
29

Explanation

This C implementation uses a hash table to track the occurrence of prefix sums, adjusted with an offset for negative indices safety, enabling identification of subarrays summing to k. The time complexity reduces to O(n), with space complexity also improving due to the hash table.