Leetcode 3Sum Closest problem solution in Python programming

In the Leetcode 3Sum Closest problem solution in Python programming Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Leetcode 3Sum Closest problem solution in Python programming

class Solution(object):
    def threeSumClosest(self, nums, target):
        nums.sort()
        
        minSum = float('inf')
        
        for anchorIdx in range(len(nums) - 2):
            leftIdx = anchorIdx + 1
            rightIdx = len(nums) - 1
            
            while leftIdx < rightIdx:
                anchor = nums[anchorIdx]
                second = nums[leftIdx]
                third = nums[rightIdx]
                
                currThreeSum = [anchor, second, third]
                currSum = sum(currThreeSum)
                
                # compare currSum with minSum w.r.t target
                if abs(currSum - target) < abs(minSum - target):
                    minSum = currSum
                
                # shift the left or right index
                if currSum < target:
                    leftIdx += 1
                elif currSum > target:
                    rightIdx -= 1
                else:
                    return currSum
                
        return minSum

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *