arrayssumtriplet

Three numbers in an array that sum up to a target sum in O(n)


Recently hashedin asked the triplet sum problem where three numbers are supposed to add up to a target sum. They said to do it in O(n).

I have tried doing it in O(n^2). First, i sorted the array and then for searching the combination i had to apply sliding window technique to all of the elements in the array. I'm not able to reduce it to O(n).

def threeNumberSum(array, targetSum):
    array.sort()
    l = len(array)
    trip = list()
    for i in range(l-2):
        left = i+1
        right = len(array)-1
        while left<right:
            currentSum = array[i] + array[left] + array[right]
            if currentSum == targetSum:
                trip.append([array[i], array[left], array[right]])
                left += 1
                right -= 1
            elif currentSum < targetSum:
                left += 1
            else:
                right -= 1
    return trip

This code actually returns all the combinations of sums possible. But according to the company, only one triplet is needed. All possible triplets are not needed


Solution

  • Thanks, everyone for trying to help. I have come up with an initial solution to do it in O(n). I am not yet sure if it's correct, but it's running on all the test case Here is a Github link to download the python file github.com/TripletInArrayWithTargetSum

    def trip(arr, target):
        d = dict()
        n = len(arr)
        for i in arr:
            d[i] = 1
    
        i = 0
        j = n - 1
        while i<j:
            s = arr[i] + arr[j]     # Calculate the sum of the elements at i and j position
            diff = target - s       # Calculate the difference needed to complete the table
            if arr[i] != diff and arr[j] != diff and diff in d: # Check if the difference exists in the hashtable and as we cannot reuse elements
                return [arr[i], arr[j], diff]                   # diff should not be equal to elements at i or j and  then return the triplet if exists
            else:
                if s > target:                                  # If difference dosent exists then we adjust pointers
                    j -= 1
                elif s == target:
                    if arr[i+1] + arr[j] < target:
                        i+=1
                    else:
                        j-=1
                else:
                    i += 1
    
        return [None]
    

    Download full file with test cases on Github