Skip to content

Commit a5a704d

Browse files
committed
feat(day 7): add two-sum target solver with brute force and hash map approches
1 parent 1ffcde8 commit a5a704d

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
================================================> Targeted Sum <====================================================================================
3+
Given an array of numbers and an integer target, find two unique numbers in the array that add up to the target value. Return an array with the indices of those two numbers, or "Target not found" if no two numbers sum up to the target.
4+
5+
The returned array should have the indices in ascending order.
6+
7+
8+
=======================================================================================================================================
9+
O/P : ====>
10+
11+
1. find_target([2, 7, 11, 15], 9) should return [0, 1].
12+
2. find_target([3, 2, 4, 5], 6) should return [1, 2].
13+
3. find_target([1, 3, 5, 6, 7, 8], 15) should return [4, 5].
14+
4. find_target([1, 3, 5, 7], 14) should return 'Target not found'.
15+
"""
16+
17+
# Brute force
18+
# Time complexity : O(n**2)
19+
# Space Complexity : O(1)
20+
def find_target_brute(arr,target):
21+
22+
n = len(arr)
23+
for i in range(n):
24+
for j in range(i+1, n):
25+
if arr[i] + arr[j] == target:
26+
return [i,j]
27+
else:
28+
return "Target not found"
29+
30+
def find_target(arr,target):
31+
c = {}
32+
for i in range(len(arr)):
33+
c[arr[i]] = i
34+
35+
for i in range(len(arr)):
36+
y = target - arr[i]
37+
38+
if y in c and c[y] != i:
39+
return [i,c[y]]
40+
else:
41+
return "Target not found"
42+
43+
44+
if __name__ == "__main__":
45+
print(find_target([2,7,11,15],9))
46+
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import unittest
2+
from targetedSum import find_target
3+
4+
class targetedSumTest(unittest.TestCase):
5+
6+
def test1(self):
7+
self.assertEqual(find_target([2,7,11,15],9),[0,1])
8+
9+
def test2(self):
10+
self.assertEqual(find_target([3,2,4,5],6),[1,2])
11+
12+
def test3(self):
13+
self.assertEqual(find_target([1,3,5,6,7,8],15),[4,5])
14+
15+
def test4(self):
16+
self.assertEqual(find_target([1,3,5,7],14),"Target not found")
17+
18+
19+
20+
if __name__ == "__main__":
21+
unittest.main()

0 commit comments

Comments
 (0)