Post

POTD #7 - Count pairs with given sum | Geeks For Geeks

POTD #7 - Count pairs with given sum | Geeks For Geeks

{% raw %}

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: 3Explanation: Pairs with sum 6 are (1, 5), (7, -1) and (1, 5). 

Input: arr[] = [1, 1, 1, 1], target = 2 Output: 6Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1).

Input: arr[] = [10, 12, 10, 15, -1], target = 125Output: 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

{% endraw %}

This post is licensed under CC BY 4.0 by the author.