Program to find k-sized list where difference between largest and smallest item is minimum in Python

Given a list of numbers and an integer k, we need to select k elements to create a sublist where the difference between the largest and smallest elements is minimized. This problem requires finding the optimal contiguous subsequence after sorting.

For example, if nums = [3, 11, 6, 2, 9] and k = 3, the output will be 4 because the best sublist we can make is [2, 3, 6] with difference 6 - 2 = 4.

Algorithm

To solve this problem, we follow these steps:

  • Sort the input list to group similar numbers together

  • Create a list to store differences for each possible k-sized window

  • For each possible starting position, calculate the difference between the largest and smallest elements in the k-sized window

  • Return the minimum difference found

Example

Here's the implementation to find the minimum difference ?

class Solution:
    def solve(self, nums, k):
        nums.sort()
        differences = []
        
        for i in range(len(nums) - k + 1):
            differences.append(nums[i + k - 1] - nums[i])
        
        return min(differences)

# Test the solution
ob = Solution()
nums = [3, 11, 6, 2, 9]
k = 3
result = ob.solve(nums, k)
print(f"Minimum difference: {result}")

# Show the sorted array and possible windows
nums_sorted = sorted(nums)
print(f"Sorted array: {nums_sorted}")
print("Possible k-sized windows:")
for i in range(len(nums_sorted) - k + 1):
    window = nums_sorted[i:i+k]
    diff = window[-1] - window[0]
    print(f"Window {window}: difference = {diff}")
Minimum difference: 4
Sorted array: [2, 3, 6, 9, 11]
Possible k-sized windows:
Window [2, 3, 6]: difference = 4
Window [3, 6, 9]: difference = 6
Window [6, 9, 11]: difference = 5

How It Works

The algorithm works by:

  1. Sorting: After sorting [3, 11, 6, 2, 9], we get [2, 3, 6, 9, 11]

  2. Sliding window: We examine each possible k-sized contiguous subsequence

  3. Calculate differences: For each window, the difference is last_element - first_element

  4. Find minimum: Return the smallest difference among all windows

Optimized Version

We can optimize by avoiding the extra list to store differences ?

def min_difference_optimized(nums, k):
    if k == 1:
        return 0
    
    nums.sort()
    min_diff = float('inf')
    
    for i in range(len(nums) - k + 1):
        diff = nums[i + k - 1] - nums[i]
        min_diff = min(min_diff, diff)
    
    return min_diff

# Test the optimized version
nums = [3, 11, 6, 2, 9]
k = 3
result = min_difference_optimized(nums, k)
print(f"Minimum difference (optimized): {result}")
Minimum difference (optimized): 4

Conclusion

The key insight is that after sorting, the optimal k-sized sublist with minimum difference will always be a contiguous subsequence. The time complexity is O(n log n) for sorting, and space complexity is O(1) for the optimized version.

---
Updated on: 2026-03-25T11:14:35+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements