-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtwo-sum.js
More file actions
76 lines (64 loc) · 1.62 KB
/
two-sum.js
File metadata and controls
76 lines (64 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Related Topics: Array, Hash Table
// Difficulty: Easy
/*
Initial thoughts:
Comparing each and every element of the array
with the remaining elements after that specific one,
we check whether they add up to the target value and
return the indices.
Time complexity: O(n^2)
Space complexity: O(1)
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) return [i, j];
}
}
};
/*
Optimization:
We could set up a lookup dictionary to reduce the
time complexity of the inner loop to O(1), trading space
for time.
Time complexity: O(n)
Space complexity: O(n)
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const lookup = {};
nums.forEach((num, i) => (lookup[num] = i));
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (lookup[complement] !== undefined && lookup[complement] !== i)
return [i, lookup[complement]];
}
};
/*
Optimization:
We can furhter optimize our solution to check for the complement
and fill the lookup dictionary in one go.
Time complexity: O(n)
Space complexity: O(n)
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const lookup = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (lookup[complement] !== undefined) return [lookup[complement], i];
else lookup[nums[i]] = i;
}
};