Skip to content

Commit 0a3f34e

Browse files
committed
added Subarray Sum Equals K (medium)
1 parent 5480b3a commit 0a3f34e

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package Medium.SubarraySumEqualsK;
2+
3+
import java.util.Arrays;
4+
5+
public class Driver {
6+
public static void main(String[] args) {
7+
Solution sol = new Solution();
8+
int[] nums = {1,1,1,2,1,2,3,5};
9+
int K = 5;
10+
System.out.println("Input: nums = " + Arrays.toString(nums) + ", k = " + K);
11+
System.out.println("Output: " + sol.subarraySum(nums, K));
12+
}
13+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
2+
# Subarray Sum Equals K
3+
[Leetcode Link](https://leetcode.com/problems/subarray-sum-equals-k/)
4+
5+
## Problem:
6+
7+
Given an array of integers and an integer **k**, you need to find the total number of continuous subarrays whose sum equals to **k**.
8+
9+
## Example:
10+
11+
```
12+
Input:nums = [1,1,1], k = 2
13+
Output: 2
14+
```
15+
16+
## Note:
17+
18+
- The length of the array is in range [1, 20,000].
19+
- The range of numbers in the array is [-1000, 1000] and the range of the integer **k** is [-1e7, 1e7].
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Medium.SubarraySumEqualsK;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class Solution {
7+
public int subarraySum(int[] nums, int k) {
8+
int numSubarray = 0;
9+
int cumSum = 0;
10+
// hashmap to keep track of cumulative sums
11+
Map<Integer, Integer> sumCount = new HashMap<>();
12+
sumCount.put(0,1);
13+
for (int num: nums) {
14+
cumSum += num;
15+
// if cumSum-k appeared in Map, then add count
16+
if (sumCount.containsKey(cumSum-k)) {
17+
numSubarray += sumCount.get(cumSum-k);
18+
}
19+
// count cumulative sum
20+
if (!sumCount.containsKey(cumSum)) {
21+
sumCount.put(cumSum, 1);
22+
} else {
23+
sumCount.put(cumSum, sumCount.get(cumSum)+1);
24+
}
25+
}
26+
return numSubarray;
27+
}
28+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Languages used: Java and Python
6767
- [Asteroid Collision](Medium/AsteroidCollision)
6868
- [Surrounded Regions](Medium/SurroundedRegions)
6969
- [Predict the Winner](Medium/PredictWinner)
70+
- [Subarray Sum Equals K](Medium/SubarraySumEqualsK)
7071
- Hard
7172
- [Maximum Score Words Formed by Letters](Hard/MaximumScoreWords)
7273
- [Reducing Dishes](Hard/ReducingDishes)

0 commit comments

Comments
 (0)