❌

Reading view

There are new articles available, click to refresh the page.

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

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

❌