Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to solve Three Number Sum in python by using For loop instead of worst time & space complexity I want to use for better understanding

sample input
array = [12, 3, 1, 2, -6, 5, -8, 6]
targetSum = 0

sample output [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]

my code is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


def threeNumberSum(array, targetSum):

    array.sort()    
    for i in range(len(array) - 2):
        nums = []
        firstNum = array[i]
        for j in range(i + 1, len(array) - 1):
            secondNum = array[j]
            for k in range(j + 1, len(array)):
                thirdNum = array[k]
                potentialTarget = firstNum + secondNum + thirdNum
                if potentialTarget == targetSum:
                    nums.append(firstNum)
                    nums.append(secondNum)
                    nums.append(thirdNum)
                    return [[firstNum, secondNum, thirdNum]]
                
    return []

Kindly suggest me how should I think. Thanks

>Solution :

I think you should place result in a list otherwise you will end the function before finding all possibilities

def threeNumberSum(array, targetSum):
    array.sort()
    possibilities = []
    for i in range(len(array) - 2): 
        firstNum = array[i]
        for j in range(i + 1, len(array) - 1):
            secondNum = array[j]
            for k in range(j + 1, len(array)):
                thirdNum = array[k]
                potentialTarget = firstNum + secondNum + thirdNum
                if potentialTarget == targetSum: 
                    possibilities.append([firstNum, secondNum, thirdNum])
    return possibilities

array = [12, 3, 1, 2, -6, 5, -8, 6]
targetSum = 0
print(threeNumberSum(array,targetSum))

answer

[[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading