Skip to content

Commit 8ef9ac7

Browse files
committed
Add solution #974
1 parent b251b7e commit 8ef9ac7

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,057 LeetCode solutions in JavaScript
1+
# 1,058 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -782,6 +782,7 @@
782782
971|[Flip Binary Tree To Match Preorder Traversal](./solutions/0971-flip-binary-tree-to-match-preorder-traversal.js)|Medium|
783783
972|[Equal Rational Numbers](./solutions/0972-equal-rational-numbers.js)|Hard|
784784
973|[K Closest Points to Origin](./solutions/0973-k-closest-points-to-origin.js)|Medium|
785+
974|[Subarray Sums Divisible by K](./solutions/0974-subarray-sums-divisible-by-k.js)|Medium|
785786
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
786787
977|[Squares of a Sorted Array](./solutions/0977-squares-of-a-sorted-array.js)|Easy|
787788
985|[Sum of Even Numbers After Queries](./solutions/0985-sum-of-even-numbers-after-queries.js)|Easy|
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 974. Subarray Sums Divisible by K
3+
* https://leetcode.com/problems/subarray-sums-divisible-by-k/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums and an integer k, return the number of non-empty subarrays
7+
* that have a sum divisible by k.
8+
*
9+
* A subarray is a contiguous part of an array.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums
14+
* @param {number} k
15+
* @return {number}
16+
*/
17+
var subarraysDivByK = function(nums, k) {
18+
const remainderCount = new Map([[0, 1]]);
19+
let sum = 0;
20+
let result = 0;
21+
22+
for (const num of nums) {
23+
sum += num;
24+
const remainder = ((sum % k) + k) % k;
25+
result += remainderCount.get(remainder) || 0;
26+
remainderCount.set(remainder, (remainderCount.get(remainder) || 0) + 1);
27+
}
28+
29+
return result;
30+
};

0 commit comments

Comments
 (0)