|
| 1 | +def two_sum(array: list[int], target: int) -> list[int]: |
| 2 | + """ |
| 3 | + Finds two indices such that the numbers at those indices add up to the target value. |
| 4 | +
|
| 5 | + This function uses a hash map (dictionary) to store the required complement |
| 6 | + for each element while iterating through the list. When a number is found |
| 7 | + that already exists in the dictionary, the indices of the two numbers are returned. |
| 8 | +
|
| 9 | + Parameters: |
| 10 | + ---------- |
| 11 | + array : list[int] |
| 12 | + A list of integers to search for the two-sum solution. |
| 13 | +
|
| 14 | + target : int |
| 15 | + The target sum that the two numbers should add up to. |
| 16 | +
|
| 17 | + Returns: |
| 18 | + ------- |
| 19 | + list[int] |
| 20 | + A list containing the indices of the two elements whose sum equals the target. |
| 21 | +
|
| 22 | + Examples: |
| 23 | + -------- |
| 24 | + >>> two_sum([2, 7, 11, 15], 9) |
| 25 | + [0, 1] |
| 26 | + >>> two_sum([3, 2, 4], 6) |
| 27 | + [1, 2] |
| 28 | + >>> two_sum([3, 3], 6) |
| 29 | + [0, 1] |
| 30 | +
|
| 31 | + Notes: |
| 32 | + ------ |
| 33 | + - Assumes exactly one valid solution exists. |
| 34 | + - The same element cannot be used twice. |
| 35 | +
|
| 36 | + Time Complexity: |
| 37 | + ---------------- |
| 38 | + O(n), where n is the length of the input list. |
| 39 | +
|
| 40 | + Space Complexity: |
| 41 | + ----------------- |
| 42 | + O(n), due to the use of a dictionary to store complements. |
| 43 | + """ |
| 44 | + |
| 45 | + dictionary: dict[int, int] = {} |
| 46 | + |
| 47 | + for i in range(len(array)): |
| 48 | + complement = target - array[i] |
| 49 | + |
| 50 | + if array[i] in dictionary: |
| 51 | + return [dictionary[array[i]], i] |
| 52 | + |
| 53 | + dictionary[complement] = i |
0 commit comments