text: Find three element from given three arrays such that their sum is X | Set 2 | Function that returns True if there exists a triplet with sum x ; Sorting arrays such that a represents smallest array ; Iterating the smallest array ; Two pointers on second and third array ; If a valid triplet is found ; Driver code
code: def existsTriplet ( a , b , c , x , l1 , l2 , l3 ) : NEW_LINE INDENT if ( l2 <= l1 and l2 <= l3 ) : NEW_LINE INDENT l1 , l2 = l2 , l1 NEW_LINE a , b = b , a NEW_LINE DEDENT elif ( l3 <= l1 and l3 <= l2 ) : NEW_LINE INDENT l1 , l3 = l3 , l1 NEW_LINE a , c = c , a NEW_LINE DEDENT for i in range ( l1 ) : NEW_LINE INDENT j = 0 NEW_LINE k = l3 - 1 NEW_LINE while ( j < l2 and k >= 0 ) : NEW_LINE INDENT if ( a [ i ] + b [ j ] + c [ k ] == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( a [ i ] + b [ j ] + c [ k ] < x ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT a = [ 2 , 7 , 8 , 10 , 15 ] NEW_LINE b = [ 1 , 6 , 7 , 8 ] NEW_LINE c = [ 4 , 5 , 5 ] NEW_LINE l1 = len ( a ) NEW_LINE l2 = len ( b ) NEW_LINE l3 = len ( c ) NEW_LINE x = 14 NEW_LINE if ( existsTriplet ( a , b , c , x , l1 , l2 , l3 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT