-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
61 lines (48 loc) · 1.98 KB
/
__init__.py
File metadata and controls
61 lines (48 loc) · 1.98 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
56
57
58
59
60
61
from typing import List
def two_sum(numbers: List[int], target: int) -> List[int]:
"""
Finds two numbers in a given list of integers which sum up to the target. This assumes the numbers are sorted in
ascending order.
Complexity:
Where n is the number of elements in the list.
Time: O(n) as the algorithm has to iterate through each element in the list
Space: O(n) as the algorithm stores each element in a dictionary that it uses to check if the element that has been
seen already sums up to the target with the current element the algorithm is iterating over.
Args:
numbers List: list of numbers
target int: Target number
Returns:
List of two numbers that sum up to the target
"""
m = {}
for idx, num in enumerate(numbers, start=1):
complement = target - num
if complement in m:
return [m[complement], idx]
m[num] = idx
return []
def two_sum_with_pointers(numbers: List[int], target: int) -> List[int]:
"""
Finds two numbers in a given list of integers which sum up to the target. This assumes the numbers are sorted in
ascending order.
Complexity:
Where n is the number of elements in the list.
Time: O(n) as the algorithm has to iterate through each element in the list
Space: O(1) as the algorithm does not store elements in a data structure and simply iterates through each element
comparing the element on the left with the element on the right
Args:
numbers List: list of numbers
target int: Target number
Returns:
List of indices of the two numbers that sum up to the target
"""
first_pointer = 0
last_pointer = len(numbers) - 1
while first_pointer < last_pointer:
result = numbers[first_pointer] + numbers[last_pointer]
if result == target:
return [first_pointer, last_pointer]
elif result < target:
first_pointer += 1
else:
last_pointer -= 1