Count quadruplets with sum K from given array | Python3 program for the above approach ; Function to return the number of quadruplets having the given sum ; Initialize answer ; Store the frequency of sum of first two elements ; Traverse from 0 to N - 1 , where arr [ i ] is the 3 rd element ; All possible 4 th elements ; Sum of last two element ; Frequency of sum of first two elements ; Store frequency of all possible sums of first two elements ; Return the answer ; Driver Code ; Given array arr [ ] ; Given sum S ; Function Call
from collections import defaultdict NEW_LINE def countSum ( a , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE m = defaultdict ( int ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT temp = a [ i ] + a [ j ] NEW_LINE if ( temp < sum ) : NEW_LINE INDENT count += m [ sum - temp ] NEW_LINE DEDENT DEDENT for j in range ( i ) : NEW_LINE INDENT temp = a [ i ] + a [ j ] NEW_LINE if ( temp < sum ) : NEW_LINE INDENT m [ temp ] += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 3 , 1 , 2 , 4 ] NEW_LINE S = 13 NEW_LINE N = len ( arr ) NEW_LINE print ( countSum ( arr , N , S ) ) NEW_LINE DEDENT