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 6cbab67

Browse files
Create two_sum.js
1 parent 09a4406 commit 6cbab67

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎algorithms/two_sum.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
3+
Return all pairs of elements which is equal to the provided sum
4+
5+
*/
6+
7+
8+
function twoSum(arr, sum){
9+
10+
let pairs = [];
11+
12+
arr.forEach(element => {
13+
14+
// counterPart = the number which makes the current element equal to the provided sum
15+
const counterPart = sum - element;
16+
17+
// if counterPart exist in array, it means pair could be made which is equal to provided sum
18+
if (arr.indexOf(counterPart) !== -1) pairs.push([element, counterPart]);
19+
20+
});
21+
22+
return pairs;
23+
24+
}
25+
26+
twoSum([1, 5, 3, 8, 6, 12, 9, 4], 7);
27+
28+
29+

0 commit comments

Comments
(0)

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