Skip to content

Commit 75f3f74

Browse files
committed
Added solutions
1 parent 7db46d5 commit 75f3f74

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

contains-duplicate/nhistoy.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
var containsDuplicate = function (nums) {
6+
// 1. Make hashmap that has previous value
7+
let map = {};
8+
// 2. Iterate nums to check nums[i] is duplicated or not
9+
for (let i = 0; i < nums.length; i++) {
10+
// 2.1 Check there is same value on the map
11+
// 3. Return true when their is duplicated value
12+
if (nums[i] in map) {
13+
return true;
14+
} else map[nums[i]] = i;
15+
}
16+
return false;
17+
};
18+
19+
// TC: O(n)
20+
// SC: O(n)
21+
22+
console.log(containsDuplicate([1, 2, 3, 1])); // true
23+
console.log(containsDuplicate([1, 2, 3, 4])); // false
24+
console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); // true

two-sum/nhistory.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var twoSum = function (nums, target) {
7+
// 1. Make a Hashmap to store { key(index) : value(target-num)}
8+
let map = {};
9+
// 2. Iterate to find value is equal to (target - nums[i])
10+
// There is only one solution
11+
for (let i = 0; i < nums.length; i++) {
12+
const diff = target - nums[i];
13+
// 3. If there is an index that has different value, return array
14+
if (diff in map) return [map[diff], i];
15+
map[nums[i]] = i;
16+
}
17+
};
18+
19+
// TC: O(n)
20+
// SC: O(n)
21+
22+
console.log(twoSum([2, 7, 11, 15], 9));
23+
console.log(twoSum([3, 2, 4], 6));

0 commit comments

Comments
 (0)