Skip to content

Commit 931a01b

Browse files
committedMar 5, 2025
Add solution #523
1 parent 23d19ff commit 931a01b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@
419419
520|[Detect Capital](./0520-detect-capital.js)|Easy|
420420
521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy|
421421
522|[Longest Uncommon Subsequence II](./0522-longest-uncommon-subsequence-ii.js)|Medium|
422+
523|[Continuous Subarray Sum](./0523-continuous-subarray-sum.js)|Medium|
422423
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
423424
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
424425
542|[01 Matrix](./0542-01-matrix.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 523. Continuous Subarray Sum
3+
* https://leetcode.com/problems/continuous-subarray-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums and an integer k, return true if nums has a good subarray
7+
* or false otherwise.
8+
*
9+
* A good subarray is a subarray where:
10+
* - its length is at least two, and
11+
* - the sum of the elements of the subarray is a multiple of k.
12+
*
13+
* Note that:
14+
* - A subarray is a contiguous part of the array.
15+
* - An integer x is a multiple of k if there exists an integer n such that x = n * k.
16+
* 0 is always a multiple of k.
17+
*/
18+
19+
/**
20+
* @param {number[]} nums
21+
* @param {number} k
22+
* @return {boolean}
23+
*/
24+
var checkSubarraySum = function(nums, k) {
25+
const map = new Map([[0, -1]]);
26+
27+
for (let i = 0, sum = 0; i < nums.length; i++) {
28+
sum += nums[i];
29+
if (k !== 0) {
30+
sum = sum % k;
31+
}
32+
33+
if (map.has(sum)) {
34+
if (i - map.get(sum) >= 2) {
35+
return true;
36+
}
37+
} else {
38+
map.set(sum, i);
39+
}
40+
}
41+
42+
return false;
43+
};

0 commit comments

Comments
 (0)