For quite some time I found my time procrastinating . Until a few days ago I stumbled upon the Daily Coding Problem (DCP) and decided to give it a shot.
The code is in python.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
def two_numbers_sums_to_k(A:list,k:int) -> bool: prev=A found=False for i in range(1,len(A)): if prev+A[i]>k: prev=min(prev,A[i]) elif prev+A[i]<k: prev=max(prev,A[i]) else: found=True break return found array=[10, 15, 3, 7] k=17 print(two_numbers_sums_to_k(array,k))
Top comments (1)
Minimum check = n(n - 1)/2