Skip to content

update two_num.py #2577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 24, 2025
Merged
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
72 changes: 52 additions & 20 deletions two_num.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,58 @@
"""Author Anurag Kumar (mailto:anuragkumarak95@gmail.com)
"""
Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com)

Given an array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Description:
This function finds two numbers in a given list that add up to a specified target.
It returns the indices of those two numbers.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Constraints:
- Each input will have exactly one solution.
- The same element cannot be used twice.

Example:
>>> two_sum([2, 7, 11, 15], 9)
[0, 1]
"""

from typing import List, Optional

def two_sum(nums: List[int], target: int) -> Optional[List[int]]:
"""
Finds indices of two numbers in 'nums' that add up to 'target'.

Args:
nums (List[int]): List of integers.
target (int): Target sum.

Returns:
Optional[List[int]]: Indices of the two numbers that add up to the target,
or None if no such pair is found.
"""
if len(nums) < 2:
raise ValueError("Input list must contain at least two numbers.")

if not all(isinstance(num, int) for num in nums):
raise TypeError("All elements in the list must be integers.")

# Dictionary to track seen values and their indices
seen_values = {}

for index, value in enumerate(nums):
complement = target - value
if complement in seen_values:
return [seen_values[complement], index]
seen_values[value] = index

return None

# Example usage
if __name__ == "__main__":
example_nums = [2, 7, 11, 15]
example_target = 9
result = two_sum(example_nums, example_target)

def twoSum(nums, target):
chk_map = {}
for index, val in enumerate(nums):
compl = target - val
if compl in chk_map:
indices = [chk_map[compl], index]
print(indices)
return [indices]
else:
chk_map[val] = index
return False
if result:
num1, num2 = example_nums[result[0]], example_nums[result[1]]
print(f"Indices that add up to {example_target}: {result} (Values: {num1} + {num2})")
else:
print(f"No combination found that adds up to {example_target}.")
Loading
Oops, something went wrong.