Program to find two pairs of numbers where difference between sum of these pairs are minimized in python

Suppose we have a list of numbers called nums and we want to select two pairs of numbers from it such that the absolute difference between the sum of these two pairs is minimized.

So, if the input is like nums = [3, 4, 5, 10, 7], then the output will be 1, as we can select these pairs (3 + 7) - (4 + 5) = 1.

Approach

To solve this problem, we will follow these steps ?

  • Create all possible pairs and calculate their absolute differences
  • Sort pairs by their differences
  • Find two pairs with no common indices that have minimum difference between their sums
  • Return the minimum difference found

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, nums):
        distances = []
        
        # Generate all possible pairs with their differences and indices
        for i in range(len(nums) - 1):
            for j in range(i + 1, len(nums)):
                distances.append((abs(nums[i] - nums[j]), i, j))
        
        # Sort pairs by their absolute differences
        distances.sort()
        
        ans = float('inf')
        
        # Find two pairs with no overlapping indices
        for i in range(len(distances) - 1):
            dist, i1, i2 = distances[i]
            j = i + 1
            
            # Find next pair with no common indices
            while j < len(distances):
                dist2, i3, i4 = distances[j]
                if len({i1, i2, i3, i4}) == 4:  # All indices are unique
                    ans = min(ans, dist2 - dist)
                    break
                j += 1
        
        return ans

# Test the solution
ob = Solution()
nums = [3, 4, 5, 10, 7]
result = ob.solve(nums)
print(f"Input: {nums}")
print(f"Minimum difference: {result}")

The output of the above code is ?

Input: [3, 4, 5, 10, 7]
Minimum difference: 1

How It Works

The algorithm works by ?

  • Pair Generation: Creates all possible pairs and calculates absolute differences between elements
  • Sorting: Sorts pairs by their differences to find closest pairs first
  • Index Checking: Ensures no element is used twice by checking all four indices are unique
  • Optimization: Returns the minimum difference between sums of valid pair combinations

Alternative Approach

Here's a more direct approach that calculates actual pair sums ?

def find_min_difference(nums):
    n = len(nums)
    min_diff = float('inf')
    
    # Generate all possible pairs
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(n):
                for l in range(k + 1, n):
                    # Ensure no overlapping indices
                    if len({i, j, k, l}) == 4:
                        sum1 = nums[i] + nums[j]
                        sum2 = nums[k] + nums[l]
                        diff = abs(sum1 - sum2)
                        min_diff = min(min_diff, diff)
    
    return min_diff

# Test with example
nums = [3, 4, 5, 10, 7]
result = find_min_difference(nums)
print(f"Input: {nums}")
print(f"Minimum difference: {result}")

The output of the above code is ?

Output: [3, 4, 5, 10, 7]
Minimum difference: 1

Conclusion

This problem requires finding two non-overlapping pairs with minimum sum difference. The optimized solution sorts pairs by differences first, making it more efficient than the brute force approach that checks all combinations directly.

Updated on: 2026-03-25T15:03:47+05:30

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements