Skip to content

Commit af75666

Browse files
committed
feat : two-sum
1 parent 22b7af4 commit af75666

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

two-sum/ekgns33.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/*
5+
input : array of integers, single integer target
6+
output : indices of the two numbers that they add up to target
7+
constraint:
8+
1) is integer positive?
9+
no [-10^9, 10^9]
10+
2) is there any duplicates?
11+
yes. but only one valid answer exists
12+
3) can i reuse elem?
13+
no
14+
15+
sol1) brute force
16+
nested for loop. tc: O(n^2), sc: O(1) when n is the length of input
17+
18+
sol2) better solution with hash map
19+
iterate through the array
20+
check if target - current elem exists
21+
if return pair of indices
22+
else save current elem and continue
23+
24+
tc : O(n), sc: O(n) when n is the length of input
25+
26+
*/
27+
class Solution {
28+
public int[] twoSum(int[] nums, int target) {
29+
Map<Integer, Integer> prev = new HashMap<>();
30+
for(int i = 0; i < nums.length; i++) {
31+
int key = target - nums[i];
32+
if(prev.containsKey(key)) {
33+
return new int[] {prev.get(key), i};
34+
}
35+
prev.put(nums[i], i);
36+
}
37+
return null;
38+
}
39+
}

0 commit comments

Comments
 (0)