Skip to content
Open
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
21 changes: 21 additions & 0 deletions Python/algorithms/arrays/two_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
def two_sum(nums, target):
"""
Finds the first pair of indices in `nums` whose values sum up to `target`.

Args:
nums (list of int): The input list of numbers.
target (int): The target sum.

Returns:
list: A list containing the two indices of the numbers that add up to target.
Returns an empty list if no such pair exists.
"""
seen = {} # Dictionary to store number -> index mapping

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

return [] # Return empty list if no pair found