Count quadruplets with sum K from given array | ''Function to return the number of quadruplets having given sum ; '' Initialize answer ; '' All possible first elements ; '' All possible second element ; '' Use map to find the  fourth element ; '' All possible third elements ; '' Calculate number of valid  4th elements ; '' Update the twice_count ; '' Unordered pairs ; '' Return answer ; ''Driver Code ; '' Given array arr[] ; '' Given sum S ; '' Function Call
def countSum ( a , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 , 1 ) : NEW_LINE INDENT req = sum - a [ i ] - a [ j ] NEW_LINE m = { } NEW_LINE for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT m [ a [ k ] ] = m . get ( a [ k ] , 0 ) + 1 NEW_LINE DEDENT twice_count = 0 NEW_LINE for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT twice_count += m . get ( req - a [ k ] , 0 ) NEW_LINE if ( req - a [ k ] == a [ k ] ) : NEW_LINE INDENT twice_count -= 1 NEW_LINE DEDENT DEDENT count += twice_count // 2 NEW_LINE 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