Skip to content

Commit d7ac18f

Browse files
committed
Add a solution to two-sum problem.
1 parent fa8a2f3 commit d7ac18f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

two-sum/joon.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
from typing import Dict
3+
4+
5+
class Solution:
6+
# Time: O(n)
7+
# Space: O(n)
8+
def twoSum(self, nums: List[int], target: int) -> List[int]:
9+
# 1. Make a map {target - num : index of num} with the list nums.
10+
# Time: O(n)
11+
# Space: O(n)
12+
mapOfSubtractedValueToIndex: Dict[int, int] = ({
13+
target - num: index for index, num in enumerate(nums)
14+
})
15+
16+
# 2. ForEach num in nums, get value from the map.
17+
# Time: O(n)
18+
# Space: O(n)
19+
result: List[int] = None
20+
for indexOfNum, num in enumerate(nums):
21+
try:
22+
indexOfSubtractedValue = mapOfSubtractedValueToIndex[num]
23+
if indexOfSubtractedValue == indexOfNum:
24+
continue
25+
# 3. Return the index of num in nums and the value from the map.
26+
return [indexOfNum, indexOfSubtractedValue]
27+
except KeyError:
28+
continue

0 commit comments

Comments
 (0)