Program to find length of longest sublist where difference between min and max smaller than k in Python

Given a list of numbers and a value k, we need to find the length of the longest sublist where the absolute difference between the largest and smallest element is ? k. This is a classic sliding window problem that can be solved efficiently using deques.

So, if the input is like nums = [2, 4, 6, 10] and k = 4, then the output will be 3, as we can select [2, 4, 6] where the absolute difference is 4.

Algorithm Approach

We use a sliding window technique with two deques to track maximum and minimum elements efficiently ?

  • Create two double-ended queues: maxd for tracking maximum, mind for tracking minimum
  • Use two pointers: i (left boundary) and j (right boundary)
  • Expand window by moving j, shrink window by moving i when difference > k
  • Maintain deques to always have maximum at front of maxd and minimum at front of mind
  • Track the maximum window size encountered

Implementation

from collections import deque

class Solution:
    def solve(self, nums, k):
        maxd = deque()  # stores maximum elements
        mind = deque()  # stores minimum elements
        i = 0
        res = 1
        
        for j, num in enumerate(nums):
            # Remove elements from maxd that are smaller than current
            while maxd and num > maxd[-1]:
                maxd.pop()
            
            # Remove elements from mind that are larger than current
            while mind and num < mind[-1]:
                mind.pop()
            
            maxd.append(num)
            mind.append(num)
            
            # Shrink window if difference exceeds k
            while maxd[0] - mind[0] > k:
                if maxd[0] == nums[i]:
                    maxd.popleft()
                if mind[0] == nums[i]:
                    mind.popleft()
                i += 1
            
            res = max(res, j - i + 1)
        
        return res

# Test the solution
solution = Solution()
nums = [2, 4, 6, 10]
k = 4
result = solution.solve(nums, k)
print(f"Longest sublist length: {result}")
Longest sublist length: 3

How It Works

The algorithm maintains two deques in a specific order ?

  • maxd: Decreasing order (largest at front)
  • mind: Increasing order (smallest at front)

For each element, we remove elements that violate the ordering, then add the current element. When the difference between maximum and minimum exceeds k, we shrink the window from the left.

Example Walkthrough

from collections import deque

def detailed_solve(nums, k):
    maxd, mind = deque(), deque()
    i, res = 0, 1
    
    print(f"Finding longest sublist in {nums} with max difference ? {k}")
    print("-" * 50)
    
    for j, num in enumerate(nums):
        print(f"Processing nums[{j}] = {num}")
        
        while maxd and num > maxd[-1]:
            maxd.pop()
        while mind and num < mind[-1]:
            mind.pop()
            
        maxd.append(num)
        mind.append(num)
        
        while maxd[0] - mind[0] > k:
            if maxd[0] == nums[i]:
                maxd.popleft()
            if mind[0] == nums[i]:
                mind.popleft()
            i += 1
        
        current_length = j - i + 1
        res = max(res, current_length)
        print(f"Window: {nums[i:j+1]}, Length: {current_length}")
        print(f"Max: {maxd[0] if maxd else None}, Min: {mind[0] if mind else None}")
        print()
    
    return res

# Test with example
nums = [2, 4, 6, 10]
k = 4
result = detailed_solve(nums, k)
print(f"Result: {result}")
Finding longest sublist in [2, 4, 6, 10] with max difference ? 4
--------------------------------------------------
Processing nums[0] = 2
Window: [2], Length: 1
Max: 2, Min: 2

Processing nums[1] = 4
Window: [2, 4], Length: 2
Max: 4, Min: 2

Processing nums[2] = 6
Window: [2, 4, 6], Length: 3
Max: 6, Min: 2

Processing nums[3] = 10
Window: [6, 10], Length: 2
Max: 10, Min: 6

Result: 3

Time and Space Complexity

  • Time Complexity: O(n) - each element is added and removed at most once
  • Space Complexity: O(n) - for the deques in worst case

Conclusion

This sliding window approach with deques efficiently finds the longest sublist where the difference between maximum and minimum elements is at most k. The deques maintain the extremes of the current window, allowing O(1) access to maximum and minimum values.

Updated on: 2026-03-25T12:37:08+05:30

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements