Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Search/Python/TwoNumbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
problem Statement :
We are given an array and a target element. We have to find the two elements in the array whose sum is equal to the target

I have provided three ways to solve the problem
i. naive way
ii. using hashtable
iii. using the sliding window algorithm
"""

# naive approach using two for loops
def twoNumberSum(arr : list, target : int) -> list :
result = list()
for i in range(len(arr)) :
for j in range(i+1, len(arr)) :
if arr[i]+arr[j] == target :
result.append((arr[i],arr[j]))
return result

# this approach uses the concept of hash table for this problem
def two_number_sum(arr : list, target : int) -> list :
nums = list();result = list()
for el in arr :
if target-el in nums :
result.append((el, target-el))
else :
nums.append(el)
return result

# this approach is called as sliding window algorithm and takes O(nlogn) time complexity
def SumOfTwo(arr, target) :
result = list()
arr.sort()
left = 0;right=len(arr)-1
while(left < right) :
if arr[left] + arr[right] == target :
result.append((arr[left], arr[right]))
left+=1;right-=1
elif arr[left] + arr[right] < target :
left+=1
elif arr[left] + arr[right] > target :
right-=1

return result

if __name__ == '__main__' :
print(SumOfTwo([3,5,-4,8,11,1,-1,6], 10))
# -4 -1 1 3 5 6 8 11