简体   繁体   中英

Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K

Problem Statement:- Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.

**def countpairs(x,length,sum):
    count = 0
    for i in range(0,length):
       for j in range(i+1,length):
            print(x[i],x[j])   
            if(x[i]+x[j]==sum):
                count+=1
    print(count)


x  = [1, 1, 1, 1]
sum = 2
length=len(x)
countpairs(x,length,sum)
Output:= 6**
This is My solution used in VS code.

My Question:- whenever I am running the same code in gfg it is not accepting the code giving me this error. I even have tried the same code in the online compiler there also it is running correctly.

This Is the gfg code which i have written 
class Solution:
    def getPairsCount(self, arr, K, N):
        count = 0
        for i in range(0,N):
           for j in range(i+1,N): 
                if(arr[i]+arr[j]==K):
                    count+=1
        return count


#Initial Template for Python 3

if __name__ == '__main__':
    tc = int(input())
    while tc > 0:
        n, k = list(map(int, input().strip().split()))
        arr = list(map(int, input().strip().split()))
        ob = Solution()
        ans = ob.getPairsCount(arr, n, k)
        print(ans)
        tc -= 1


Error
if(arr[i]+arr[j]==K):
IndexError: list index out of range

There's no added value in using a class for this. You just need:-

def getPairsCount(arr, K):
  count = 0
  for i in range(len(arr)-1):
    if arr[i] + arr[i+1] == K:
      count += 1
  return count

EDIT:

Previous answer assumed that only adjacent elements were to be considered. If that's not the case then try this:-

import itertools

def getPairsCount(arr, K):
    count = 0
    for c in itertools.combinations(sorted(arr), 2):
        if c[0] + c[1] == K:
            count += 1
    return count

data = [1, 2, 1, 4, -1]
print(getPairsCount(data, 3))

We do not need two loops for this question. Here is something that runs in O(n) :

def countpairs(list_,K):
    count = 0
    set_ = set(list_)
    pairs_ = []
    
    for val in list_:
        if K - val in set_:
            # we ensure that pairs are unordered by using min and max
            pairs_.append ( (min(val, K-val), max(val, K-val)) )
            count+=1

    set_pairs = set(pairs_)
    
    print ("Pairs which sum up to ",K," are: ", set_pairs)

    return len(set_pairs)




x  = [1,4,5,8,2,0,24,7,6]
sum_ = 13
print ("Total count of pairs summming up to ", sum_, " = ", countpairs(x, sum_))

Output:

Pairs which sum up to  13  are:  {(6, 7), (5, 8)}
Total count of pairs summming up to  13  =  2

The idea is that if two values should sum to a value K , we can iterate through the array and check if there is another element in the array which when paired with the current element, sums up to K . The inner loop in your solution can be replaced with a search using the in . Now, we need this search to be fast ( O(1) per element ), so we create a set out of our input array ( set_ in my example).

def solve(a,K):
    freq = {}
    for v in a:
        if v in freq:
            freq[v] += 1
        else:
            freq[v] = 1
    for i in range(len(set(a))):
        res += freq[a[i]] * freq[K - a[i]]
    return res

a = [int(v) for v in input().split()]
K = int(input())
print(solve(a,K))
def solve(a,K):
    freq = {}
    for v in a:
        if v in freq:
            freq[v] += 1
        else:
            freq[v] = 1
    for i in range(len(set(a))):
        res += freq[a[i]] * freq[K - a[i]]
    return res 

a = [int(v) for v in input().split()]
K = int(input())
print(solve(a,K))
# Time Complexity : O(N)
# Space Complexity : O(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM