POTD #7 β Count pairs with given sum | Geeks For Geeks
26 December 2024 at 18:50
Problem Statement
Geeks For Geeks β https://www.geeksforgeeks.org/problems/count-pairs-with-given-sumβ150253/1
Given an arrayΒ arr[]Β and an integerΒ target.Β You have to find numbers of pairs in arrayΒ arr[]Β which sums up to givenΒ target.
Input: arr[] = [1, 5, 7, -1, 5], target = 6 Output: 3 Explanation: Pairs with sum 6 are (1, 5), (7, -1) and (1, 5).
Input: arr[] = [1, 1, 1, 1], target = 2 Output: 6 Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1).
Input: arr[] = [10, 12, 10, 15, -1], target = 125 Output: 0
My Approach
Todayβs problem is similar to Two Sum problem, but with a counter.
class Solution: #Complete the below function def countPairs(self,arr, target): #Your code here hash_count = {} total_count = 0 for num in arr: rem = target - num if hash_count.get(rem): total_count += hash_count.get(rem) hash_count[num] = hash_count.get(num, 0) + 1 return total_count