From 7805ce9479687c82c3f1e2dfa91610ada9b47986 Mon Sep 17 00:00:00 2001 From: Ankit Kumar Date: Fri, 2 Oct 2020 20:43:47 +0530 Subject: [PATCH] Finding two numbers sum --- Search/Python/TwoNumbers.py | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Search/Python/TwoNumbers.py diff --git a/Search/Python/TwoNumbers.py b/Search/Python/TwoNumbers.py new file mode 100644 index 0000000..f85f5ec --- /dev/null +++ b/Search/Python/TwoNumbers.py @@ -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 \ No newline at end of file