File tree 2 files changed +48
-0
lines changed 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class KSumSubarrays {
2
+ public int kSumSubarrays (int [] nums , int k ) {
3
+ int n = nums .length ;
4
+ int count = 0 ;
5
+ // Populate the prefix sum array, setting its first element to 0.
6
+ int [] prefixSum = new int [nums .length + 1 ];
7
+ for (int i = 0 ; i < n ; i ++) {
8
+ prefixSum [i +1 ] = prefixSum [i ] + nums [i ];
9
+ }
10
+ // Loop through all valid pairs of prefix sum values to find all
11
+ // subarrays that sum to 'k'.
12
+ for (int j = 1 ; j < n + 1 ; j ++) {
13
+ for (int i = 1 ; i < j + 1 ; i ++) {
14
+ if (prefixSum [j ] - prefixSum [i - 1 ] == k ) {
15
+ count ++;
16
+ }
17
+ }
18
+ }
19
+ return count ;
20
+ }
21
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
3
+
4
+ public class KSumSubarraysOptimized {
5
+ public int kSumSubarraysOptimized (int [] nums , int k ) {
6
+ int count = 0 ;
7
+ // Initialize the map with 0 to handle subarrays that sum to 'k'
8
+ // from the start of the array.
9
+ Map <Integer , Integer > prefixSumMap = new HashMap <>();
10
+ prefixSumMap .put (0 , 1 );
11
+ int currPrefixSum = 0 ;
12
+ for (int num : nums ) {
13
+ // Update the running prefix sum by adding the current number.
14
+ currPrefixSum += num ;
15
+ // If a subarray with sum 'k' exists, increment 'count' by the
16
+ // number of times it has been found.
17
+ if (prefixSumMap .containsKey (currPrefixSum - k )) {
18
+ count += prefixSumMap .get (currPrefixSum - k );
19
+ }
20
+ // Update the frequency of 'curr_prefix_sum' in the hash map.
21
+ int freq = prefixSumMap .getOrDefault (currPrefixSum , 0 );
22
+ prefixSumMap .put (currPrefixSum , freq + 1 );
23
+ }
24
+ return count ;
25
+ }
26
+
27
+ }
You can’t perform that action at this time.
0 commit comments