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