Skip to content

Commit c7d153a

Browse files
📦 NEW: Solve Array Easy problem - Two sum
1 parent 05ba9cc commit c7d153a

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@ Solve [LeetCode](https://leetcode.com) problems using JavaScript By Topic wise w
33

44
---
55

6-
## Array Problems -
6+
## Array Problems Solution -
77
1. [Two Sum](https://leetcode.com/problems/two-sum/) - [Solution](https://github.com/ManiruzzamanAkash/LeetCode-In-JS/blob/main/two-sum/)

two-sum/index.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Two sum Problem leetcode.
3+
*
4+
* @param {number[]} nums
5+
* @param {number} target
6+
*
7+
* @return {number[]}
8+
*/
9+
var twoSum = function(nums, target) {
10+
const hashmap = {};
11+
for (let i = 0; i < nums.length; i++) {
12+
const diff = target - nums[i];
13+
14+
// If the difference is in the hashmap, return the indices.
15+
if (diff in hashmap) { // or, hashmap[diff] !== undefined
16+
return [hashmap[diff], i];
17+
}
18+
19+
// Otherwise, add the current number to the hashmap.
20+
hashmap[nums[i]] = i;
21+
}
22+
23+
return [];
24+
};
25+
26+
module.exports = twoSum;

two-sum/index.test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const twoSum = require("./index");
2+
3+
test("[2, 7, 11, 15] array and target 9 would result [0, 1]", () => {
4+
expect(twoSum([2, 7, 11, 15], 9)).toStrictEqual([0, 1]);
5+
});
6+
7+
test("[3, 3] array and target 6 would result [0, 1]", () => {
8+
expect(twoSum([3, 3], 6)).toStrictEqual([0, 1]);
9+
});
10+
11+
test("[3, 2, 4] array and target 6 would result [1, 2]", () => {
12+
expect(twoSum([3, 2, 4], 6)).toStrictEqual([1, 2]);
13+
});
14+
15+
test("[3, 2, 3] array and target 6 would result [0, 2]", () => {
16+
expect(twoSum([3, 2, 3], 6)).toStrictEqual([0, 2]);
17+
});

0 commit comments

Comments
 (0)