DEV Community

sakshishreyaa
sakshishreyaa

Posted on

Daily Coding Problem: Problem #1 [Easy]

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.

Problem #1
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?

My solution

def two_numbers_sums_to_k(A:list,k:int) -> bool:
    prev=A[0]
    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))      
Enter fullscreen mode Exit fullscreen mode

Oldest comments (1)

Collapse
 
faranaiki profile image
Muhammad Faran Aiki

Minimum check = n(n - 1)/2

def check(A, k): # Do not want to dirty my hand with some colon and arrow
    for i in range(0, len(A)):
        for j in range(i + 1, len(A)):
            if (A[i] + A[j] == k): return True
    return False
Enter fullscreen mode Exit fullscreen mode