|
| 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 | + |
0 commit comments