Program to find three unique elements from list whose sum is closest to k Python

Given a list of numbers and a target value k, we need to find three unique elements whose sum is closest to k and return the absolute difference between their sum and k.

For example, if nums = [2, 5, 25, 6] and k = 14, the triplet [2, 5, 6] gives us the sum 13, which is closest to 14 with an absolute difference of 1.

Approach

We'll use a two-pointer technique after sorting the array:

  1. Sort the input list to enable two-pointer traversal
  2. For each element as the first element of the triplet, use two pointers to find the optimal pair
  3. Track the minimum absolute difference found so far

Algorithm Steps

  • Sort the list nums
  • Initialize min_diff to a large value (infinity)
  • For each index i from 0 to length of nums:
    • Set left = i + 1 and right = len(nums) - 1
    • While left < right:
      • Calculate current_sum = nums[i] + nums[left] + nums[right]
      • If current_sum <= target, update minimum difference and move left pointer right
      • Otherwise, update minimum difference and move right pointer left
  • Return the minimum difference

Implementation

def find_closest_triplet_sum(nums, target):
    nums.sort()
    min_diff = float('inf')
    
    for i in range(len(nums) - 2):
        left = i + 1
        right = len(nums) - 1
        
        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]
            diff = abs(current_sum - target)
            min_diff = min(min_diff, diff)
            
            if current_sum < target:
                left += 1
            elif current_sum > target:
                right -= 1
            else:
                # Found exact match
                return 0
    
    return min_diff

# Test the function
nums = [2, 5, 25, 6]
k = 14
result = find_closest_triplet_sum(nums, k)
print(f"Input: nums = {nums}, k = {k}")
print(f"Closest triplet sum difference: {result}")
Input: nums = [2, 5, 25, 6], k = 14
Closest triplet sum difference: 1

How It Works

After sorting [2, 5, 25, 6] becomes [2, 5, 6, 25]. The algorithm finds:

  • Triplet [2, 5, 6] with sum 13, difference from 14 is 1
  • Triplet [2, 5, 25] with sum 32, difference from 14 is 18
  • Triplet [2, 6, 25] with sum 33, difference from 14 is 19
  • Triplet [5, 6, 25] with sum 36, difference from 14 is 22

The minimum difference is 1 from the triplet [2, 5, 6].

Example with Different Input

# Test with another example
nums = [1, 3, 5, 7, 9]
k = 15
result = find_closest_triplet_sum(nums, k)
print(f"Input: nums = {nums}, k = {k}")
print(f"Closest triplet sum difference: {result}")

# The triplet [3, 5, 7] gives sum 15, exactly matching k
Input: nums = [1, 3, 5, 7, 9], k = 15
Closest triplet sum difference: 0

Time and Space Complexity

  • Time Complexity: O(n²) where n is the length of the input list
  • Space Complexity: O(1) excluding the space used for sorting

Conclusion

The two-pointer technique provides an efficient solution to find the triplet with sum closest to the target. By sorting the array first, we can systematically explore all possible triplets while maintaining optimal time complexity.

Updated on: 2026-03-25T11:41:05+05:30

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements