Program to find the sum of the lengths of two nonoverlapping sublists whose sum is given in Python

Given a list of numbers and a target value k, we need to find two nonoverlapping sublists whose sum equals k and return the sum of their lengths. When multiple solutions exist, we choose the two shortest sublists.

Problem Understanding

For example, with nums = [7, 10, -2, -1, 4, 3] and k = 7, we can find sublists [7] (length 1) and [4, 3] (length 2), giving us a total length of 3. We don't choose [10, -2, -1] because it's longer than [7].

Algorithm Approach

The solution uses a two-pass approach with prefix and suffix arrays to efficiently find the shortest sublists ?

  1. Prefix Pass: For each position, find the shortest sublist ending at or before that position with sum k
  2. Suffix Pass: For each position, find the shortest sublist starting at or after that position with sum k
  3. Combine Results: Try all possible split points and find the minimum sum of lengths

Example

class Solution:
    def solve(self, A, target):
        INF = float("inf")
        N = len(A)
        
        # Prefix array: shortest sublist ending at or before position i
        prefix = [INF] * N
        last = {0: -1}  # cumulative sum -> last position
        s = 0
        
        for i in range(N):
            s += A[i]
            # Find if there's a sublist ending at i with sum = target
            if s - target in last:
                prefix[i] = i - last[s - target]
            else:
                prefix[i] = INF
            last[s] = i
        
        # Update prefix to store minimum length up to each position
        for i in range(1, N):
            prefix[i] = min(prefix[i], prefix[i - 1])
        
        # Suffix array: shortest sublist starting at or after position i
        suffix = [INF] * N
        last = {0: N}
        s = 0
        
        for i in range(N - 1, -1, -1):
            s += A[i]
            if s - target in last:
                suffix[i] = last[s - target] - i
            else:
                suffix[i] = INF
            last[s] = i
        
        # Update suffix to store minimum length from each position
        for i in range(N - 2, -1, -1):
            suffix[i] = min(suffix[i], suffix[i + 1])
        
        # Find minimum sum of lengths for all valid split points
        ans = min(prefix[i] + suffix[i + 1] for i in range(N - 1))
        
        return ans if ans < INF else -1

# Test the solution
ob = Solution()
nums = [7, 10, -2, -1, 4, 3]
k = 7
result = ob.solve(nums, k)
print(f"Input: {nums}, target: {k}")
print(f"Output: {result}")
Input: [7, 10, -2, -1, 4, 3], target: 7
Output: 3

How It Works

The algorithm maintains cumulative sums and uses hash maps to track positions where specific sums occur. For each position, it calculates the shortest valid sublist and then combines results from both directions to find the optimal solution.

Test with Another Example

# Test with different input
nums2 = [1, 2, 3, 4, 5]
k2 = 5
result2 = ob.solve(nums2, k2)
print(f"Input: {nums2}, target: {k2}")
print(f"Output: {result2}")
Input: [1, 2, 3, 4, 5], target: 5
Output: 2

Conclusion

This solution efficiently finds two nonoverlapping sublists with the given sum using prefix and suffix arrays. The time complexity is O(n) and space complexity is O(n), making it optimal for this problem.

Updated on: 2026-03-25T11:45:29+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements