Program to find number of sublists with sum k in a binary list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary list with 0s or 1s. We also have another input called k, we have to find the number of sublists whose sum is same as k.

So, if the input is like nums = [1, 0, 0, 1, 1, 1, 0, 1] k = 3, then the output will be 8 because the sublists are [1,0,0,1,1], [0,0,1,1,1], [0,0,1,1,1,0], [0,1,1,1], [0,1,1,1,0], [1,1,1], [1,1,1,0] [1,1,0,1].

To solve this, we will follow these steps −

  • sums := a map initially contains valye 1 for key 0
  • r_sum := 0
  • ans := 0
  • for each x in nums, do
    • r_sum := r_sum + x
    • ans := ans + (sums[r_sum - k] if (r_sum - k) is present, otherwise 0)
    • sums[r_sum] := 1 + (sums[r_sum - k] if (r_sum - k) is present, otherwise 0)
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(nums, k):
   sums = {0: 1}
   r_sum = 0
   ans = 0

   for x in nums:
      r_sum += x
      ans += sums.get(r_sum - k, 0)
      sums[r_sum] = sums.get(r_sum, 0) + 1

   return ans

nums = [1, 0, 0, 1, 1, 1, 0, 1]
k = 3
print(solve(nums, k))

Input

[1, 0, 0, 1, 1, 1, 0, 1], 3

Output

8
raja
Updated on 16-Oct-2021 10:05:13

Advertisements