Program to find number of sublists whose sum is given target in python

Suppose we have a list of numbers called nums and another value target, we have to find the number of sublists whose sum is same as target.

So, if the input is like nums = [3, 0, 3] and target = 3, then the output will be 4, as we have these sublists whose sum is 3: [3], [3, 0], [0, 3], [3].

Algorithm Approach

To solve this, we will follow these steps ?

  • temp := an empty map
  • temp[0] := 1
  • s := 0
  • ans := 0
  • for i in range 0 to size of nums, do
    • s := s + nums[i]
    • comp := s - target
    • if comp is in temp, then
      • ans := ans + temp[comp]
    • temp[s] := temp[s] + 1
  • return ans

Example

Let us see the following implementation to get better understanding ?

from collections import defaultdict

class Solution:
    def solve(self, nums, target):
        temp = defaultdict(int)
        temp[0] = 1
        s = 0
        ans = 0
        for i in range(len(nums)):
            s += nums[i]
            comp = s - target
            if comp in temp:
                ans += temp[comp]
            temp[s] += 1
        return ans

ob = Solution()
nums = [3, 0, 3]
target = 3
print(ob.solve(nums, target))

The output of the above code is ?

4

How It Works

The algorithm uses a prefix sum technique with a hash map. For each position, it calculates the cumulative sum and checks if there's a previous prefix sum that, when subtracted from the current sum, equals the target. The key insight is that if prefix_sum[j] - prefix_sum[i] = target, then the subarray from index i+1 to j has sum equal to target.

Alternative Approach

Here's a simpler version without using a class ?

def count_sublists_with_target_sum(nums, target):
    from collections import defaultdict
    
    prefix_sum_count = defaultdict(int)
    prefix_sum_count[0] = 1
    
    current_sum = 0
    result = 0
    
    for num in nums:
        current_sum += num
        complement = current_sum - target
        
        if complement in prefix_sum_count:
            result += prefix_sum_count[complement]
        
        prefix_sum_count[current_sum] += 1
    
    return result

# Test the function
nums = [3, 0, 3]
target = 3
print(count_sublists_with_target_sum(nums, target))
4

Conclusion

The prefix sum approach efficiently counts sublists with a target sum in O(n) time complexity. By storing cumulative sums in a hash map, we can quickly find how many previous sums, when subtracted from the current sum, equal our target.

Updated on: 2026-03-25T12:45:05+05:30

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements