Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 48c4712

Browse files
Continuous Subarray Sum
1 parent c5d8b32 commit 48c4712

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

‎0523_continuousSubarraySum.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} nums Array of integers.
3+
* @param {number} target Sum target of subarray elements.
4+
* @return {boolean} True if subarray of at least length 2 exists which elements add up to target
5+
* @summary Two Sum {@link https://leetcode.com/problems/continuous-subarray-sum/}
6+
* @description Given an array of integers, return indices of the two numbers such that they add up to a specific target.
7+
* Space O(t) - dictionary with at most size of target entries.
8+
* Time O(n) - we iterate through nums array once.
9+
*/
10+
const checkSubarraySum = (nums, target) => {
11+
const lookup = { 0: -1 };
12+
let movingModulo = 0;
13+
14+
for (let index = 0; index < nums.length; index++) {
15+
movingModulo += nums[index];
16+
if (target !== 0) movingModulo = movingModulo % target;
17+
18+
if (lookup[movingModulo] !== undefined) {
19+
if (index - lookup[movingModulo] >= 2) return true;
20+
} else lookup[movingModulo] = index;
21+
}
22+
23+
return false;
24+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /