Skip to content

Commit 78cbd3e

Browse files
committed
feat(arrays): two sum
1 parent 20f7bf8 commit 78cbd3e

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

algorithms/arrays/two_sum/README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Two Sum - Input Array Is Sorted
2+
3+
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that
4+
they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <=
5+
index1 < index2 <= numbers.length.
6+
7+
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
8+
9+
The tests are generated such that there is exactly one solution. You may not use the same element twice.
10+
11+
Your solution must use only constant extra space.
12+
13+
```text
14+
15+
Example 1:
16+
17+
Input: numbers = [2,7,11,15], target = 9
18+
Output: [1,2]
19+
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
20+
```
21+
22+
```text
23+
Example 2:
24+
25+
Input: numbers = [2,3,4], target = 6
26+
Output: [1,3]
27+
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
28+
```
29+
30+
```text
31+
Example 3:
32+
33+
Input: numbers = [-1,0], target = -1
34+
Output: [1,2]
35+
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
36+
```
37+
38+
## Related Topics
39+
40+
- Array
41+
- Two Pointers
42+
- Binary Search

algorithms/arrays/two_sum/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from typing import List
2+
3+
4+
def two_sum(numbers: List[int], target: int) -> List[int]:
5+
m = {}
6+
7+
for idx, num in enumerate(numbers, start=1):
8+
complement = target - num
9+
10+
if complement in m:
11+
return [m[complement], idx]
12+
m[num] = idx
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import unittest
2+
from . import two_sum
3+
4+
5+
class TwoSumTestCase(unittest.TestCase):
6+
def test_1(self):
7+
"""numbers = [2,7,11,15], target = 9"""
8+
numbers = [2, 7, 11, 15]
9+
target = 9
10+
expected = [1, 2]
11+
actual = two_sum(numbers, target)
12+
self.assertEqual(expected, actual)
13+
14+
def test_2(self):
15+
"""numbers = [2,3,4], target = 6"""
16+
numbers = [2, 3, 4]
17+
target = 6
18+
expected = [1, 3]
19+
actual = two_sum(numbers, target)
20+
self.assertEqual(expected, actual)
21+
22+
def test_3(self):
23+
"""numbers = [-1,0], target = -1"""
24+
numbers = [-1, 0]
25+
target = -1
26+
expected = [1, 2]
27+
actual = two_sum(numbers, target)
28+
self.assertEqual(expected, actual)
29+
30+
31+
if __name__ == '__main__':
32+
unittest.main()

0 commit comments

Comments
 (0)