- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)]
- if (target - (k + z)) is in m, then
- for each z in D, do
- for each j in B, do
- return count
Let us see the following implementation to get better understanding:
Example
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