Skip to content

Commit ab85227

Browse files
committed
add solution: two-sum
1 parent b506385 commit ab85227

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

two-sum/dusunax.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
# 1. Two Sum
3+
4+
use a hash map to store the numbers and their indices.
5+
iterate through the list and check if the complement of the current number (target - nums[i]) is in the hash map.
6+
7+
(assume that each input would have exactly one solution)
8+
- if it is a pairNum, return the indices of the two numbers.
9+
- if it is not, add the current number and its index to the hash map.
10+
11+
12+
## Time and Space Complexity
13+
14+
```
15+
TC: O(n)
16+
SC: O(n)
17+
```
18+
19+
#### TC is O(n):
20+
- iterating through the list just once to find the two numbers. = O(n)
21+
22+
#### SC is O(n):
23+
- using a hash map to store the numbers and their indices. = O(n)
24+
'''
25+
26+
class Solution:
27+
def twoSum(self, nums: List[int], target: int) -> List[int]:
28+
map = {}
29+
for i in range(len(nums)):
30+
pairNum = target - nums[i]
31+
if pairNum in map:
32+
return [map.get(pairNum), i]
33+
map[nums[i]] = i

0 commit comments

Comments
 (0)