|
1 |
| -"""Author Anurag Kumar (mailto:[email protected]) |
| 1 | +""" |
| 2 | +Author: Anurag Kumar (mailto:[email protected]) |
2 | 3 |
|
3 |
| -Given an array of integers, return indices of the two numbers |
4 |
| -such that they add up to a specific target. |
5 |
| -You may assume that each input would have exactly one solution, |
6 |
| -and you may not use the same element twice. |
| 4 | +Description: |
| 5 | + This function finds two numbers in a given list that add up to a specified target. |
| 6 | + It returns the indices of those two numbers. |
7 | 7 |
|
8 |
| -Example: |
9 |
| -Given nums = [2, 7, 11, 15], target = 9, |
10 |
| -Because nums[0] + nums[1] = 2 + 7 = 9, |
11 |
| -return [0, 1]. |
| 8 | +Constraints: |
| 9 | + - Each input will have exactly one solution. |
| 10 | + - The same element cannot be used twice. |
12 | 11 |
|
| 12 | +Example: |
| 13 | + >>> two_sum([2, 7, 11, 15], 9) |
| 14 | + [0, 1] |
13 | 15 | """
|
14 | 16 |
|
| 17 | +from typing import List, Optional |
| 18 | + |
| 19 | +def two_sum(nums: List[int], target: int) -> Optional[List[int]]: |
| 20 | + """ |
| 21 | + Finds indices of two numbers in 'nums' that add up to 'target'. |
| 22 | +
|
| 23 | + Args: |
| 24 | + nums (List[int]): List of integers. |
| 25 | + target (int): Target sum. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + Optional[List[int]]: Indices of the two numbers that add up to the target, |
| 29 | + or None if no such pair is found. |
| 30 | + """ |
| 31 | + if len(nums) < 2: |
| 32 | + raise ValueError("Input list must contain at least two numbers.") |
| 33 | + |
| 34 | + if not all(isinstance(num, int) for num in nums): |
| 35 | + raise TypeError("All elements in the list must be integers.") |
| 36 | + |
| 37 | + # Dictionary to track seen values and their indices |
| 38 | + seen_values = {} |
| 39 | + |
| 40 | + for index, value in enumerate(nums): |
| 41 | + complement = target - value |
| 42 | + if complement in seen_values: |
| 43 | + return [seen_values[complement], index] |
| 44 | + seen_values[value] = index |
| 45 | + |
| 46 | + return None |
| 47 | + |
| 48 | +# Example usage |
| 49 | +if __name__ == "__main__": |
| 50 | + example_nums = [2, 7, 11, 15] |
| 51 | + example_target = 9 |
| 52 | + result = two_sum(example_nums, example_target) |
15 | 53 |
|
16 |
| -def twoSum(nums, target): |
17 |
| - chk_map = {} |
18 |
| - for index, val in enumerate(nums): |
19 |
| - compl = target - val |
20 |
| - if compl in chk_map: |
21 |
| - indices = [chk_map[compl], index] |
22 |
| - print(indices) |
23 |
| - return [indices] |
24 |
| - else: |
25 |
| - chk_map[val] = index |
26 |
| - return False |
| 54 | + if result: |
| 55 | + num1, num2 = example_nums[result[0]], example_nums[result[1]] |
| 56 | + print(f"Indices that add up to {example_target}: {result} (Values: {num1} + {num2})") |
| 57 | + else: |
| 58 | + print(f"No combination found that adds up to {example_target}.") |
0 commit comments