Skip to content

Commit 74e6b56

Browse files
authored
Update Two Sum - Leetcode 1.py
1 parent bfef124 commit 74e6b56

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Two Sum - Leetcode 1/Two Sum - Leetcode 1.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
# Brute Force Solution
2+
class Solution:
3+
def twoSum(self, nums: List[int], target: int) -> List[int]:
4+
n = len(nums)
5+
for i in range(n):
6+
for j in range(n):
7+
if nums[i] + nums[j] == target and i != j:
8+
return (i, j)
9+
# Time: O(n^2)
10+
# Space: O(1)
11+
12+
# Better Brute Force Solution
13+
class Solution:
14+
def twoSum(self, nums: List[int], target: int) -> List[int]:
15+
n = len(nums)
16+
for i in range(n):
17+
for j in range(i+1, n):
18+
if nums[i] + nums[j] == target:
19+
return (i, j)
20+
# Time: O(n^2)
21+
# Space: O(1)
22+
23+
# 2-Pass Optimal Solution
124
class Solution:
225
def twoSum(self, nums: List[int], target: int) -> List[int]:
326
h = {}
@@ -9,6 +32,19 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
932

1033
if y in h and h[y] != i:
1134
return [i, h[y]]
35+
# Time Complexity: O(n)
36+
# Space Complexity: O(n)
1237

38+
# One-Pass Optimal Solution (For Bootcamp)
39+
class Solution:
40+
def twoSum(self, nums: List[int], target: int) -> List[int]:
41+
h = {}
42+
n = len(nums)
43+
for i, x in enumerate(nums):
44+
y = target - nums[i]
45+
if y in h:
46+
return [i, h[y]]
47+
else:
48+
h[x] = i
1349
# Time Complexity: O(n)
1450
# Space Complexity: O(n)

0 commit comments

Comments
 (0)