From acdd16bcebfd1e06e6e093140bde783d4e957a3e Mon Sep 17 00:00:00 2001 From: Shaily Tripathi <123561590+shaz12t@users.noreply.github.com> Date: Sat, 22 Jul 2023 15:42:08 +0530 Subject: [PATCH] Create dsa.py made a change in idea --- algorithms/Python/dictionaries/dsa.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 algorithms/Python/dictionaries/dsa.py diff --git a/algorithms/Python/dictionaries/dsa.py b/algorithms/Python/dictionaries/dsa.py new file mode 100644 index 00000000..d1886540 --- /dev/null +++ b/algorithms/Python/dictionaries/dsa.py @@ -0,0 +1,25 @@ +def two_sum(nums, target): + # Create a dictionary to store the elements and their indices + num_dict = {} + + # Traverse the array + for i, num in enumerate(nums): + # Calculate the complement required to reach the target + complement = target - num + + # Check if the complement exists in the dictionary + if complement in num_dict: + # Return the indices of the two numbers that add up to the target + return [num_dict[complement], i] + + # Store the current element and its index in the dictionary + num_dict[num] = i + + # If no pair is found, return [-1, -1] + return [-1, -1] + +# Test example +nums = [2, 7, 11, 15] +target = 9 +result = two_sum(nums, target) +print(result) # Output: [0, 1] (Because nums[0] + nums[1] = 2 + 7 = 9)