From 66e07d61379abcdc8aa9a8aac9e729c5987ae71e Mon Sep 17 00:00:00 2001 From: Shagun Vishnoi Date: Wed, 29 Oct 2025 00:13:22 +0530 Subject: [PATCH] added an optimised two sum code in python --- Python/algorithms/arrays/two_sum.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/algorithms/arrays/two_sum.py diff --git a/Python/algorithms/arrays/two_sum.py b/Python/algorithms/arrays/two_sum.py new file mode 100644 index 00000000..597bef07 --- /dev/null +++ b/Python/algorithms/arrays/two_sum.py @@ -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