Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sumOfTwo Time Limit Exceeded CodeFights Interview Practice

I am attempting the sumOFTwo challenge on CodeFights.com but I unfortuantly cannot complete it to view the solution. All my tests suceedd until the 15th hidden test and it says it exceeds the time limit.

The challenge is - You have two integer arrays, a and b, and an integer target value v. Determine whether there is a pair of numbers, where one number is taken from a and the other from b, that can be added together to get a sum of v. Return true if such a pair exists, otherwise return false.

My code is -

def sumOfTwo(a,b,v):
    a.sort()
    b.sort()

    if(0 in a and v in b):
        return True
    elif(v in a and 0 in b):
        return True
    else:
        for i in a:
            for j in b:
                if(i + j == v):
                    return True
    return False

I know it could be shrunken down to about 6 lines of code, but I kept adding in lines that could help the code possibly finish quicker. Are there any other optimizations I am missing.

like image 227
Wyman Gray Avatar asked Jun 20 '26 01:06

Wyman Gray


1 Answers

You could just turn one of the lists to set, iterate over the other list and see if v - value_from_list exists in the set:

def sumOfTwo(a,b,v):
    b = set(b)

    return any(v - x in b for x in a)

print(sumOfTwo([3, 6, 7], [2, 1], 9))
print(sumOfTwo([3, 6, 7], [2, 1], 10))
print(sumOfTwo([3, 6, 7], [2, 1], 4))
print(sumOfTwo([3, 6, 7], [2, 1], 3))

Output:

True
False
True
False

Time complexity of above in O(n).

like image 157
niemmi Avatar answered Jun 23 '26 02:06

niemmi