File tree 1 file changed +25
-0
lines changed
1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums Array of numbers.
3
+ * @param {number } k Goal sum of valid subarray.
4
+ * @return {number } Count of subarrays for which elements sum up to k.
5
+ * @summary Subarray Sum Equals K {@link https://leetcode.com/problems/subarray-sum-equals-k/}
6
+ * @description Given array of integers and goal sum, return number of subarrays for which sum of elements equal k.
7
+ * Space O(n) - Creating object literal (hashmap) with up to n keys.
8
+ * Time O(n) - Input is traversed nums.length times.
9
+ */
10
+ const subarraySum = ( nums , k ) => {
11
+ let count = 0 ;
12
+ let sum = 0 ;
13
+ const results = {
14
+ 0 : 1 ,
15
+ } ;
16
+
17
+ const length = nums . length ;
18
+ for ( let i = 0 ; i < length ; i ++ ) {
19
+ sum += nums [ i ] ;
20
+ if ( results [ sum - k ] ) count += results [ sum - k ] ;
21
+ results [ sum ] = results [ sum ] ? results [ sum ] + 1 : 1 ;
22
+ }
23
+
24
+ return count ;
25
+ } ;
You can’t perform that action at this time.
0 commit comments