-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_sum_of_K.py
More file actions
executable file
·40 lines (33 loc) · 1.12 KB
/
find_sum_of_K.py
File metadata and controls
executable file
·40 lines (33 loc) · 1.12 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
# add two element from the list to check if the sum equals to a variable k
def find_pair_sum(nums, target):
# # 1. Using the Hash Map
# seen= {}
# for num in nums:
# complement = target-num
# if complement in seen:
# return complement , num
# else:
# seen[num] = True
# return None
# Logic ==> the complement will be the k-num where it will be c= 15-num = num+c == K, so when each complement is stroed in hastable
# dict of seen and searching if the complement c = num in the nums list , means the complement of new num is found in seen then its result
# 2. Using the Two Pointer
#def find_pair_sum(nums, target):
nums.sort()
l , r = 0 ,len(nums)-1
while l<r:
current_sum = nums[l]+ nums[r]
if current_sum == k:
return nums[l], nums[r], [l,r]
elif current_sum < k:
l += 1
else:
r -= 1
return None
# Example usage
nums = [3,2,4]
k = 6
result = find_pair_sum(nums, k)
print(result) # Output: (7, 8)
# first assign the l and r 0 and array -1 to traverse
# than compare if the