Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions leetcode/two_sum/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,16 @@ class Solution:
# Space: O(n)
def two_sum(self, nums: list[int], target: int) -> list[int]:
seen: dict[int, int] = {}
answers: list[list[int]] = []

for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
answer = [seen[complement], i]
answers.append(answer)
seen[num] = i
return []

if len(answers) > 1:
raise ValueError(f"Found {len(answers)} answers in the solution: {answers}")

return answers[0] if answers else []
2 changes: 1 addition & 1 deletion leetcode/two_sum/test_solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def setup_method(self):
([-3, 4, 3, 90], 0, [0, 2]),
([1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2], 6, [5, 11]),
([2, 1, 9, 4, 4, 56, 90, 3], 8, [3, 4]),
([89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], 185, [3, 4]),
([89, 90, 91, 92, 93, 97, 98, 99], 185, [3, 4]),
([-1000000000, 1000000000], 0, [0, 1]),
([0, 1], 1, [0, 1]),
([1, 2], 5, []),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
"([-3, 4, 3, 90], 0, [0, 2])",
"([1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2], 6, [5, 11])",
"([2, 1, 9, 4, 4, 56, 90, 3], 8, [3, 4])",
"([89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], 185, [3, 4])",
"([89, 90, 91, 92, 93, 97, 98, 99], 185, [3, 4])",
"([-1000000000, 1000000000], 0, [0, 1])",
"([0, 1], 1, [0, 1])",
"([1, 2], 5, [])",
Expand Down