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

PythonServer Side ProgrammingProgramming

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] target = 3, then the output will be 4, as we have these sublists whose sum is 3: [3], [3, 0], [0, 3], [3].

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

Let us see the following implementation to get better understanding:

Example Code

Live Demo

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))

Input

[3, 0, 3], 3

Output

4
raja
Published on 25-Nov-2020 12:59:39
Advertisements