Program to find number of distinct quadruple that forms target sum in python



Suppose we have four lists of numbers A, B, C, and D, and also have a target value, we have to find the number of distinct quadruple (i, j, k, l) such that A[i] + B[j] + C[k] + D[l] is same as target.

So, if the input is like A = [5, 4, 3] B = [8, 4] C = [6, 2] D = [4, 10] target = 23, then the output will be 3, the quadruples are [5, 8, 6, 4] [3, 4, 6, 10] [3, 8, 2, 10].

To solve this, we will follow these steps:

  • count := 0
  • m := an empty map
  • for each i in A, do
    • for each j in B, do
      • m[i + j] := m[i + j] + 1
    • for each k in C, do
      • for each z in D, do
        • if (target - (k + z)) is in m, then
          • count := count + m[target - (k + z)]
  • return count

Let us see the following implementation to get better understanding:

Example

Live Demo

class Solution:
   def solve(self, A, B, C, D, target):
      count = 0
      from collections import defaultdict
      from collections import Counter

      m = defaultdict(int)
      for i in A:
         for j in B:
            m[i + j] += 1

      for k in C:
         for z in D:
            if target - (k + z) in m:
               count += m[target - (k + z)]
      return count

ob = Solution()
A = [5, 4, 3]
B = [8, 4]
C = [6, 2]
D = [4, 10]
target = 23
print(ob.solve(A, B, C, D, target))

Input

[5, 4, 3], [8, 4], [6, 2], [4, 10], 23

Output

3

Advertisements