Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’.
Examples:
Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are (1, 5), (7, -1) & (1, 5) Input : arr[] = {1, 1, 1, 1}, sum = 2 Output : 6 There are 3! pairs with sum 2. Input : arr[] = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}, sum = 11 Output : 9
Expected time complexity O(n)
Naive Solution – A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum.
PHP
<?php // PHP implementation of simple // method to find count of // pairs with given sum. // Returns number of pairs in // arr[0..n-1] with sum equal // to 'sum' function getPairsCount( $arr , $n , $sum ) { // Initialize result $count = 0; // Consider all possible pairs // and check their sums for ( $i = 0; $i < $n ; $i ++) for ( $j = $i + 1; $j < $n ; $j ++) if ( $arr [ $i ] + $arr [ $j ] == $sum ) $count ++; return $count ; } // Driver Code $arr = array (1, 5, 7, -1, 5) ; $n = sizeof( $arr ); $sum = 6; echo "Count of pairs is " , getPairsCount( $arr , $n , $sum ); // This code is contributed by nitin mittal. ?> |
Count of pairs is 3
Time Complexity: O(n2)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!