Coding Problem 3
Sum of Numbers in List
asked by Google
Ques. Given a list of numbers and a integer K return whether any two numbers from the list will add upto K or not. For example -
Given list is [10, 15, 3, 7] and K = 17, then return True because 10 + 7 = 17.
Solution.
So basically we have to find the two numbers that are present in the list and sum of both is equal to K. So we can simply run two loops on the list and check each pair of number if they are equal to K or not. This method is Brute-force and complexity is O(n^2).
What we can do here is run the loop over the list and then subtract that number from the target and check whether the remaining number is present in the list or not. Lets see the code
def find_numbers(inp_list, K):
for i in inp_list:
if (K - i) in inp_list:
return True
return False
inp_list = [10, 15, 3, 7]
K = 17
print(find_numbers(inp_list, K))
This method will work and we can take K and input_list as a input from the user.
This problem can be solved by other method also. By using dictionary we can solve it. While iterating the list if (K-num) is in dictionary then we will return True else we will save the current element into the dictionary.
def find_nums(l, k):
d = {}
for i in l:
if k-i in d:
return True
else:
d[i] = i
return False
l = [12, 3, 4, 13, 7]
K = 11
print(find_nums(l, K))
Comments
Post a Comment