Skip to content

Commit 1ec9296

Browse files
committed
solved: two_sum using a dictionary and algebra complement idea. -@iamserda
1 parent 94768a1 commit 1ec9296

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def two_sum(self, nums: list[int], target: int) -> list[int]:
3+
complements = {}
4+
for index, num in enumerate(nums):
5+
complements[num] = index
6+
complement = target - num
7+
if complement in complements:
8+
return [complements[complement], index]
9+
10+
11+
arr = [3, 4, 5, 6]
12+
target = 7
13+
sol = Solution()
14+
assert sol.two_sum(arr, target) == [0, 1] # efficient solution, O(n) time, O(n) space

0 commit comments

Comments
 (0)